-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.js
226 lines (213 loc) · 6.81 KB
/
provider.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
'use strict';
const path = require('path');
const slugify = require('slugify');
const { Storage } = require('@google-cloud/storage');
/**
* lodash _.get native port
*
* checkout: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_get
*
* Another solution is use destructor variable with default value as {} on each layer
* but it appears so tricky.
*
* const { a: { b: { c: d = 42 } = {} } = {} } = object
*/
const get = (obj, path, defaultValue = undefined) => {
const travel = (regexp) =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
/**
* Check validity of Service Account configuration
* @param config
* @returns {{private_key}|{client_email}|{project_id}|any}
*/
const checkServiceAccount = (config = {}) => {
if (!config.bucketName) {
throw new Error('"Bucket name" is required!');
}
if (!config.baseUrl) {
/** Set to default **/
config.baseUrl = 'https://storage.googleapis.com/{bucket-name}';
}
if (!config.basePath) {
config.basePath = '';
}
if (config.publicFiles === undefined) {
config.publicFiles = true;
}
if (!config.uniform) {
config.uniform = false;
}
if (!config.skipCheckBucket) {
config.skipCheckBucket = false;
}
let serviceAccount;
if (config.serviceAccount) {
try {
serviceAccount =
typeof config.serviceAccount === 'string'
? JSON.parse(config.serviceAccount)
: config.serviceAccount;
} catch (e) {
throw new Error(
'Error parsing data "Service Account JSON", please be sure to copy/paste the full JSON file.'
);
}
/**
* Check exist
*/
if (!serviceAccount.project_id) {
throw new Error(
'Error parsing data "Service Account JSON". Missing "project_id" field in JSON file.'
);
}
if (!serviceAccount.client_email) {
throw new Error(
'Error parsing data "Service Account JSON". Missing "client_email" field in JSON file.'
);
}
if (!serviceAccount.private_key) {
throw new Error(
'Error parsing data "Service Account JSON". Missing "private_key" field in JSON file.'
);
}
}
return serviceAccount;
};
/**
* Check bucket exist, or create it
* @param GCS
* @param bucketName
* @returns {Promise<void>}
*/
const checkBucket = async (GCS, bucketName) => {
let bucket = GCS.bucket(bucketName);
const [exists] = await bucket.exists();
if (!exists) {
throw new Error(
`An error occurs when we try to retrieve the Bucket "${bucketName}". Check if bucket exist on Google Cloud Platform.`
);
}
};
/**
* Merge uploadProvider config with gcs key in custom Strapi config
* @param providerConfig
* @returns {{private_key}|{client_email}|{project_id}|any}
*/
const mergeConfigs = (providerConfig) => {
const customGcsConfig = get(strapi, 'config.gcs', {});
const customEnvGcsConfig = get(strapi, 'config.currentEnvironment.gcs', {});
return { ...providerConfig, ...customGcsConfig, ...customEnvGcsConfig };
};
/**
* Generate upload filename including path
*
* @param basePath
* @param file
* @returns string
*/
const generateUploadFileName = (basePath, file) => {
const backupPath =
file.related && file.related.length > 0 && file.related[0].ref
? `${file.related[0].ref}`
: `${file.hash}`;
const filePath = file.path ? `${file.path}/` : `${backupPath}/`;
const extension = file.ext.toLowerCase();
const fileName = slugify(path.basename(file.hash));
return `${basePath}${filePath}${fileName}${extension}`;
};
/**
*
* @param providerConfig
* @returns {{upload(*=): Promise<void>, delete(*): Promise<undefined>}}
*/
const init = (providerConfig) => {
const config = mergeConfigs(providerConfig);
const serviceAccount = checkServiceAccount(config);
let GCS;
if (serviceAccount) {
// Provide service account credentials
GCS = new Storage({
projectId: serviceAccount.project_id,
credentials: {
client_email: serviceAccount.client_email,
private_key: serviceAccount.private_key,
},
});
} else {
// Storage will attempt to find Application Default Credentials
GCS = new Storage();
}
const basePath = `${config.basePath}/`.replace(/^\/+/, '');
const baseUrl = config.baseUrl.replace('{bucket-name}', config.bucketName);
return {
async upload(file) {
try {
const fullFileName =
typeof config.generateUploadFileName === 'function'
? config.generateUploadFileName(file)
: generateUploadFileName(basePath, file);
if (!config.skipCheckBucket) {
await checkBucket(GCS, config.bucketName);
}
const bucket = GCS.bucket(config.bucketName);
const bucketFile = bucket.file(fullFileName);
const [fileExists] = await bucketFile.exists();
if (fileExists) {
console.info('File already exists. Try to remove it.');
await this.delete(file);
}
const fileAttributes = {
contentType:
typeof config.getContentType === 'function' ? config.getContentType(file) : file.mime,
gzip: typeof config.gzip === 'boolean' ? config.gzip : 'auto',
metadata:
typeof config.metadata === 'function'
? config.metadata(file)
: {
contentDisposition: `inline; filename="${file.name}"`,
cacheControl: `public, max-age=${config.cacheMaxAge || 3600}`,
},
};
if (!config.uniform) {
fileAttributes.public = config.publicFiles;
}
await bucketFile.save(file.buffer, fileAttributes);
file.url = `${baseUrl}/${fullFileName}`;
console.debug(`File successfully uploaded to ${file.url}`);
} catch (error) {
// Re-throw so that the upload operation will fail
// and error will surface to the user in the Strapi admin front-end
console.error(`Error uploading file to Google Cloud Storage: ${error.message}`);
throw error;
}
},
async delete(file) {
const fileName = file.url.replace(`${baseUrl}/`, '');
const bucket = GCS.bucket(config.bucketName);
try {
await bucket.file(fileName).delete();
console.debug(`File ${fileName} successfully deleted`);
} catch (error) {
if (error.code === 404) {
console.warn('Remote file was not found, you may have to delete manually.');
}
// based on last code, it will never throw (resolves and rejects)
// throw error;
}
},
};
};
module.exports = {
get,
checkServiceAccount,
checkBucket,
mergeConfigs,
generateUploadFileName,
init,
};