dapps-images-model.js
1 const logger = require('../logger/logger').getLoggerFor('DAPPS-Images-Model'); 2 const IPFSService = require('./../services/ipfs-service'); 3 const mongoose = require('mongoose'); 4 const Schema = mongoose.Schema; 5 6 let DAppsImageSchema = new Schema({ 7 id: Schema.Types.ObjectId, 8 content: String, 9 hash: { 10 type: String, 11 unique: true, 12 } 13 }); 14 15 DAppsImageSchema.pre('save', async function () { 16 const content = this.content.split('base64,')[1]; 17 if (!content) { 18 throw new Error('Invalid base64 image'); 19 } 20 const data = Buffer.from(content, 'base64'); 21 const hash = await IPFSService.addContent(data); 22 this.set({ content, hash }); 23 }); 24 25 DAppsImageSchema.statics.findByContent = async function (input) { 26 const content = input.split('base64,')[1]; 27 const data = Buffer.from(content, 'base64'); 28 const hash = await IPFSService.generateContentHash(data); 29 30 return this.findOne({ hash }); 31 }; 32 33 module.exports = mongoose.model('DAppsImage', DAppsImageSchema);