dapps-metadata-model.js
1 let mongoose = require('mongoose'); 2 let Schema = mongoose.Schema; 3 4 const bs58 = require('bs58'); 5 const validator = require('validator'); 6 7 const dappCategories = require('./../constants/dapp-categories').ALL_CATEGORIES; 8 const metadataStatuses = require('./../constants/dapp-metadata-statuses').ALL_STATUSES; 9 10 const IPFSService = require('./../services/ipfs-service'); 11 12 let DAppsMetadataSchema = new Schema({ 13 id: Schema.Types.ObjectId, 14 details: { 15 name: { 16 type: String, 17 required: true 18 }, 19 uploader: { 20 type: String, 21 required: true 22 }, 23 url: { 24 type: String, 25 required: true 26 }, 27 description: { 28 type: String, 29 required: true 30 }, 31 category: { 32 type: String, 33 required: true, 34 enum: dappCategories 35 }, 36 image: { 37 type: String, 38 required: true 39 }, 40 dateAdded: { 41 type: Number, 42 required: true 43 }, 44 }, 45 email: { 46 type: String, 47 required: true, 48 validate: { 49 validator: function (value) { 50 return validator.isEmail(value); 51 }, 52 message: props => `${props.value} is not a valid email!` 53 } 54 }, 55 hash: { 56 type: String, 57 unique: true, 58 }, 59 compressedMetadata: String, 60 status: { 61 type: String, 62 default: "NEW", 63 enum: metadataStatuses 64 }, 65 /* This is used for new IPFS hash when DApp changes status */ 66 ipfsHash: String 67 }); 68 69 DAppsMetadataSchema.pre('save', async function () { 70 const hash = await IPFSService.addContent(this.details); 71 /* We set ipfsHash so even unapproved DApps have it set */ 72 this.set({ hash, ipfsHash: hash }); 73 }); 74 75 DAppsMetadataSchema.statics.findByPlainMetadata = async function (metadata) { 76 const hash = await IPFSService.generateContentHash(metadata); 77 return this.findOne({ hash }); 78 } 79 80 DAppsMetadataSchema.statics.findByBytes32Hash = async function (bytes32Hash) { 81 const hashHex = `1220${bytes32Hash.slice(2)}`; 82 const hashBytes = Buffer.from(hashHex, 'hex'); 83 const encodedHash = bs58.encode(hashBytes); 84 85 return this.findOne({ hash: encodedHash }); 86 } 87 88 module.exports = mongoose.model('DAppsMetadata', DAppsMetadataSchema);