forked from jjaburke91/strapi-provider-upload-bunnynet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (58 loc) · 2.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"use strict"
const axios = require("axios")
const { ApplicationError } = require("@strapi/utils").errors
const DEFAULT_UPLOAD_LIMIT_MB = 200
module.exports = {
init({ api_key, storage_zone, pull_zone, max_content_length, max_body_length }) {
if (!api_key || !storage_zone || !pull_zone) {
throw new ApplicationError("BUNNY_API_KEY, BUNNY_STORAGE_ZONE or BUNNY_PULL_ZONE can't be null or undefined.")
}
const bunny_api = axios.create({
baseURL: `https://storage.bunnycdn.com/${storage_zone}/`,
timeout: 0,
headers: {
AccessKey: api_key,
"content-type": "application/octet-stream",
},
maxContentLength: max_content_length || (1024 * 1024 * DEFAULT_UPLOAD_LIMIT_MB),
maxBodyLength: max_body_length || (1024 * 1024 * DEFAULT_UPLOAD_LIMIT_MB)
})
const upload = (file) =>
new Promise(async (resolve, reject) => {
const data = file.stream || Buffer.from(file.buffer, "binary")
try {
const response = await bunny_api.put(`${file.hash}${file.ext}`, data)
if (response.data.HttpCode !== 201) {
reject(new Error(`Error uploading to Bunny.net: ${error.message}`))
}
file.url = `${pull_zone}/${file.hash}${file.ext}`
resolve()
} catch (error) {
reject(new Error(`Error uploading to Bunny.net: ${error.message}`))
}
})
return {
upload(file) {
return upload(file)
},
uploadStream(file) {
return upload(file)
},
delete: async (file) => {
return new Promise(async (resolve, reject) => {
try {
const response = await bunny_api.delete(`${file.hash}${file.ext}`)
if (response.data.HttpCode !== 200) {
console.error("Soft Error: Failed to delete file; has it already been deleted?", response.data)
resolve()
}
resolve()
} catch (error) {
console.error("Soft Error: Failed to delete file; has it already been deleted?", error.message)
resolve()
}
})
},
}
},
}