aboutsummaryrefslogtreecommitdiffstats
path: root/apps/Notes/models/Note.js
blob: c8cf854b463b3de0d5eb74febdb762e5e60f86b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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 { _id: note._id, 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 { _id: note._id, 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