2020-01-23 13:20:38 +01:00
|
|
|
const logger = require('../logger/logger').getLoggerFor('DAPPS-Images-Model');
|
2019-06-03 21:01:42 +03:00
|
|
|
const IPFSService = require('./../services/ipfs-service');
|
2020-01-23 13:20:38 +01:00
|
|
|
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 () {
|
2020-01-23 13:20:38 +01:00
|
|
|
const content = this.content.split('base64,')[1];
|
|
|
|
if (!content) {
|
2019-06-03 21:01:42 +03:00
|
|
|
throw new Error('Invalid base64 image');
|
|
|
|
}
|
2020-01-23 13:20:38 +01:00
|
|
|
const data = Buffer.from(content, 'base64');
|
|
|
|
const hash = await IPFSService.addContent(data);
|
|
|
|
this.set({ content, hash });
|
2019-06-03 21:01:42 +03:00
|
|
|
});
|
|
|
|
|
2020-02-14 11:04:49 +01:00
|
|
|
DAppsImageSchema.statics.findByContent = async function (input) {
|
|
|
|
const content = input.split('base64,')[1];
|
2020-01-23 13:20:38 +01:00
|
|
|
const data = Buffer.from(content, 'base64');
|
|
|
|
const hash = await IPFSService.generateContentHash(data);
|
2019-06-03 21:01:42 +03:00
|
|
|
|
2020-01-23 13:20:38 +01:00
|
|
|
return this.findOne({ hash });
|
2019-06-03 21:01:42 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = mongoose.model('DAppsImage', DAppsImageSchema);
|