summaryrefslogtreecommitdiff
path: root/lib/db/index.js
blob: 1c7cc15e8cb3526580e962d8d97f1ac00c36a910 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var db = module.exports

var connection = require("./bookshelf")
var bookshelf = connection.bookshelf
var knex = connection.knex

var Folder = db.Folder = bookshelf.Model.extend({
  tableName: 'folders',
  hasTimestamps: true,
})
var File = db.File = bookshelf.Model.extend({
  tableName: 'files',
  hasTimestamps: true,
})
var Job = db.Job = bookshelf.Model.extend({
  tableName: 'jobs',
  hasTimestamps: true,
})
var Task = db.Task = bookshelf.Model.extend({
  tableName: 'tasks',
  hasTimestamps: true,
})

db.crud = 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)
    },
  }
}

function memoize (f) {
  const o = {}
  return (model) => {
    console.log(model)
    t = model.toString()
    if (o[t]) {
      return o[t]
    }
    o[t] = f(model)
    return o[t]
  }
}