diff options
author | 2021-09-09 23:23:53 +0200 | |
---|---|---|
committer | 2021-09-09 23:23:53 +0200 | |
commit | a863c77ea12a4c7060b9c496e5df81bbdcca2374 (patch) | |
tree | 8d38ebc21928fa973235d8829bf1c6f7d65028df /apps/Notes/models/Note.js | |
parent | 569bdb8c5d7538fa0ea8a99ff2f8376f7cbfa51a (diff) | |
download | my_apps-a863c77ea12a4c7060b9c496e5df81bbdcca2374.tar.gz my_apps-a863c77ea12a4c7060b9c496e5df81bbdcca2374.tar.bz2 my_apps-a863c77ea12a4c7060b9c496e5df81bbdcca2374.zip |
add db transactions, move db models
Diffstat (limited to 'apps/Notes/models/Note.js')
-rw-r--r-- | apps/Notes/models/Note.js | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/apps/Notes/models/Note.js b/apps/Notes/models/Note.js new file mode 100644 index 0000000..0f4b3f9 --- /dev/null +++ b/apps/Notes/models/Note.js @@ -0,0 +1,37 @@ +const { encrypt, decrypt } = require('helpers/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 = encrypt(note.content) + } + + next() +}) + +const Note = mongoose.models.Note || mongoose.model('Note', noteSchema) + +export default Note |