diff options
author | 2021-08-12 19:00:50 +0200 | |
---|---|---|
committer | 2021-08-12 19:00:50 +0200 | |
commit | 74abb7052d3af3c305cfe3c525aea311ccc446e1 (patch) | |
tree | 752f6da94ea8b554906774d878ecebfbfe8d724e /models | |
parent | 0660d3f5d3028ab3084c77f14a350d74c567bbd7 (diff) | |
download | my_apps-74abb7052d3af3c305cfe3c525aea311ccc446e1.tar.gz my_apps-74abb7052d3af3c305cfe3c525aea311ccc446e1.tar.bz2 my_apps-74abb7052d3af3c305cfe3c525aea311ccc446e1.zip |
crypt notes content
Diffstat (limited to 'models')
-rw-r--r-- | models/Note.js | 30 |
1 files changed, 29 insertions, 1 deletions
diff --git a/models/Note.js b/models/Note.js index 1790c91..3f94e62 100644 --- a/models/Note.js +++ b/models/Note.js @@ -1,8 +1,36 @@ +const {encrypt, decrypt} = require('lib/crypt') const mongoose = require('mongoose') const noteSchema = new mongoose.Schema({ content: {type: String, required: true, minlength: 1}, -}); +}) + +noteSchema.statics.getNote = async (id) => { + const note = await Note.findById(id) + if (!note) throw new Error('Could not fetch note') + + const content = decrypt(note.content) + + return {...note, content} +} + +noteSchema.statics.updateNote = async (id, content) => { + const note = await Note.findByIdAndUpdate(id, {content: encrypt(content)}, {new: true}) + + if (!note) throw new Error('Could not update note') + + return {...note, content} +} + +noteSchema.pre('save', async function(next){ + const note = this; + + if (note.isModified('content')) { + note.content = await encrypt(note.content) + } + + next() +}) const Note = mongoose.models.Note || mongoose.model('Note', noteSchema) |