summaryrefslogtreecommitdiff
path: root/lib/db/crud.js
blob: fb326900688b3fe8a67ecbe5637ad1464af06821 (plain)
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
38
39
40
module.exports = function(model) {
  return {
    index: (q) => {
      return model.query( (qb) => {
        const limit = q.limit || 100
        const offset = q.offset || 0
        if (limit) {
          delete q.limit
        }
        if (q.offset) {
          delete q.offset
        }
        if (Object.keys(q).length > 0) qb.where(q)
        qb.orderBy("id", "desc")
        if (limit) qb.limit( limit )
        if (offset) qb.offset( offset )
        // console.log(qb)
        return qb
      }).fetchAll()
    },
    show: (id) => {
      return new model({'id': id}).fetch()
    },
    show_ids: (ids) => {
      return model.query( (qb) => {
        qb.whereIn('id', ids)
        return qb
      }).fetchAll()
    },
    create: (data) => {
      return new model(data).save()
    },
    update: (id, data) => {
      return new model({'id': id}).save(data)
    },
    destroy: (id) => {
      return new model({'id': id}).destroy(data)
    },
  }
}