-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
106 lines (95 loc) · 2.62 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
'use strict'
const baseProvider = {
extend (obj) {
Object.assign(this, obj)
},
upload () {
throw new Error('Provider upload method is not implemented')
},
delete () {
throw new Error('Provider delete method is not implemented')
}
}
const { convertToStrapiError } = require('../strapi-plugin-upload/errors')
const wrapFunctionForErrors = fn => async (...args) => {
try {
return await fn(...args)
} catch (err) {
throw convertToStrapiError(err)
}
}
const getProviderData = (file, options) => {
if (!options.selectProvider || typeof options.selectProvider !== 'function') {
const msg = `config must define a selectProvider function`
strapi.log.error(msg)
throw new Error(msg)
}
let providerKey
try {
providerKey = options.selectProvider(file)
} catch (err) {
const msg = `The function selectProvider generated error`
strapi.log.error(msg)
strapi.log.error(err)
throw new Error(msg)
}
if (!options.providers) {
const msg = `You must set providers object in providerOptions of config/plugins.js`
strapi.log.error(msg)
throw new Error(msg)
}
const p = options.providers[providerKey]
if (!p) {
const msg = `The upload provider selector with key '${providerKey}' not found`
strapi.log.error(msg)
throw new Error(msg)
}
let providerInstance
try {
providerInstance = require(`strapi-provider-upload-${p.provider}`).init(
p.options
)
} catch (err) {
const msg = `The provider package isn't installed. Please run \`npm install strapi-provider-upload-${p.provider}\``
strapi.log.error(msg)
throw new Error(msg)
}
const providerFunctions = Object.assign(Object.create(baseProvider), {
...providerInstance,
upload: wrapFunctionForErrors(file => {
return providerInstance.upload(file, p.options)
}),
delete: wrapFunctionForErrors(file => {
return providerInstance.delete(file, p.options)
})
})
return { providerFunctions, providerOptions: p.options }
}
module.exports = {
init (options) {
return {
upload (file) {
try {
const { providerFunctions, providerOptions } = getProviderData(
file,
options
)
return providerFunctions.upload(file, providerOptions)
} catch (err) {
return null
}
},
delete (file) {
try {
const { providerFunctions, providerOptions } = getProviderData(
file,
options
)
return providerFunctions.delete(file, providerOptions)
} catch (err) {
return null
}
}
}
}
}