1
0
mirror of https://github.com/dap-ps/discover.git synced 2025-02-07 15:05:07 +00:00
discover/back-end/models/dapps-images-model.js

34 lines
1015 B
JavaScript
Raw Normal View History

const logger = require('../logger/logger').getLoggerFor('DAPPS-Images-Model');
2019-06-03 21:01:42 +03:00
const IPFSService = require('./../services/ipfs-service');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
2019-06-03 21:01:42 +03:00
let DAppsImageSchema = new Schema({
id: Schema.Types.ObjectId,
content: String,
hash: {
type: String,
unique: true,
}
});
DAppsImageSchema.pre('save', async function () {
const content = this.content.split('base64,')[1];
if (!content) {
2019-06-03 21:01:42 +03:00
throw new Error('Invalid base64 image');
}
const data = Buffer.from(content, 'base64');
const hash = await IPFSService.addContent(data);
this.set({ content, hash });
2019-06-03 21:01:42 +03:00
});
DAppsImageSchema.statics.findByContent = async function (content) {
const content = content.split('base64,')[1];
const data = Buffer.from(content, 'base64');
const hash = await IPFSService.generateContentHash(data);
2019-06-03 21:01:42 +03:00
return this.findOne({ hash });
2019-06-03 21:01:42 +03:00
};
module.exports = mongoose.model('DAppsImage', DAppsImageSchema);