dapp-image-service.js
1 const DAppImage = require('./../models/dapps-images-model'); 2 3 class DAppImageService { 4 5 static async upload(req, image) { 6 try { 7 const uploadedImage = await DAppImage.create({ content: image }); 8 return buildImageUrl(req, uploadedImage.hash); 9 } catch (error) { 10 // Code 11000 is because of uniqueness, so just return the already exist document 11 if (error.code == 11000) { 12 const existingImage = await DAppImage.findByContent(image); 13 return buildImageUrl(req, existingImage.hash); 14 } 15 16 throw new Error(error.message); 17 } 18 19 } 20 21 static async retrieveImage(imageHash) { 22 return DAppImage.findOne({ 'hash': imageHash }); 23 } 24 } 25 26 const buildImageUrl = function (req, imageHash) { 27 return `/metadata/image/${imageHash}`; 28 } 29 30 module.exports = DAppImageService;