57 lines
1.4 KiB
JavaScript
Raw Normal View History

'use strict';
2018-03-24 12:08:07 +01:00
/**
* Module dependencies
*/
// Public node modules.
const cloudinary = require('cloudinary').v2;
const intoStream = require('into-stream');
2018-03-24 12:08:07 +01:00
module.exports = {
init(config) {
cloudinary.config(config);
2018-03-24 12:08:07 +01:00
return {
upload(file, customConfig = {}) {
2018-03-24 12:08:07 +01:00
return new Promise((resolve, reject) => {
2019-04-27 12:09:07 +02:00
const upload_stream = cloudinary.uploader.upload_stream(
{ resource_type: 'auto', ...customConfig },
2019-04-27 12:09:07 +02:00
(err, image) => {
if (err) {
return reject(err);
}
file.url = image.secure_url;
file.provider_metadata = {
public_id: image.public_id,
resource_type: image.resource_type,
};
2019-04-27 12:09:07 +02:00
resolve();
}
2019-04-27 12:09:07 +02:00
);
2018-03-24 12:08:07 +01:00
intoStream(file.buffer).pipe(upload_stream);
2018-05-04 18:27:39 +02:00
});
2018-03-24 12:08:07 +01:00
},
async delete(file, customConfig = {}) {
2018-03-24 12:08:07 +01:00
try {
const { resource_type, public_id } = file.provider_metadata;
const response = await cloudinary.uploader.destroy(public_id, {
2019-04-27 12:09:07 +02:00
invalidate: true,
resource_type: resource_type || 'image',
...customConfig,
2018-03-24 12:08:07 +01:00
});
if (response.result !== 'ok') {
2018-03-24 12:08:07 +01:00
throw {
2019-04-27 12:09:07 +02:00
error: new Error(response.result),
2018-05-04 18:27:39 +02:00
};
2018-03-24 12:08:07 +01:00
}
} catch (error) {
throw error.error;
}
2019-04-27 12:09:07 +02:00
},
2018-03-24 12:08:07 +01:00
};
2019-04-27 12:09:07 +02:00
},
2018-03-24 12:08:07 +01:00
};