summaryrefslogtreecommitdiff
path: root/app/server/db/crud.js
blob: 78dfc6ee281551c3eac0e5902e67e7f6415e0b17 (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
41
42
43
44
45
46
47
module.exports = function(model) {
  return {
    index: (q) => {
      return model.query( (qb) => {
        const limit = q.limit || 100
        const offset = q.offset || 0
        const orderBy = q.orderBy || 'id desc'
        if (limit) {
          delete q.limit
        }
        if (q.offset) {
          delete q.offset
        }
        delete q.orderBy
        if (Object.keys(q).length > 0) qb.where(q)
        if (orderBy) {
          const ob = orderBy.split(" ")
          const ob_field = ob[0] || 'id'
          const ob_dir = ob[1] || 'desc'
          qb.orderBy(ob_field, ob_dir)
        }
        if (limit) qb.limit( limit )
        if (offset) qb.offset( offset )
        // console.log(qb)
        return qb
      }).fetchAll()
    },
    show: (id, field='id') => {
      return new model({[field]: 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()
    },
  }
}