controllers/base.js   A
last analyzed

Size

Lines of Code 215

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
nc 3
dl 0
loc 215
rs 10
noi 6

1 Function

Rating   Name   Duplication   Size   Complexity  
A base.js ➔ ??? 0 5 1
1
var Router = require('express')
2
var pluralize = require('pluralize')
3
var ok = require('./utils').ok
4
var fail = require('./utils').fail
5
var respond = require('./utils').respond
6
const logger = require('winston')
0 ignored issues
show
Unused Code introduced by
The constant logger seems to be never used. Consider removing it.
Loading history...
7
const MAX_RESULTS = 100
0 ignored issues
show
Unused Code introduced by
The constant MAX_RESULTS seems to be never used. Consider removing it.
Loading history...
8
9
/**
10
  Generic controller that provides CRUD operations for a given Mongoose model
11
*/
12
module.exports = class BaseController {
13
14
  /**
15
    @param model Mongoose model
16
    @param key primary key of the model that will be used for searching, removing
17
    and reading
18
  */
19
  constructor(model, key) {
20
    this.model = model
21
    this.modelName = model.modelName.toLowerCase()
22
    this.key = key
23
  }
24
25
  create(data) {
26
    return this.model
27
      .create(data)
28
      .then((modelInstance) => {
29
        var response = {}
30
        response[this.modelName] = modelInstance
31
        return response
32
      })
33
  }
34
35
  read(id) {
36
    var filter = {}
37
    filter[this.key] = id
38
39
    return this.model
40
      .findOne(filter)
41
      .then((modelInstance) => {
42
        var response = {}
43
        response[this.modelName] = modelInstance
44
        return response
45
      })
46
  }
47
48
  list() {
49
    return this.model
50
      .find({})
51
      .limit(MAX_RESULTS)
0 ignored issues
show
Bug introduced by
The variable MAX_RESULTS seems to be never declared. If this is a global, consider adding a /** global: MAX_RESULTS */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
52
      .then((modelInstances) => {
53
        var response = {}
54
        response[pluralize(this.modelName)] = modelInstances
55
        return response
56
      })
57
  }
58
59
  delete(id) {
60
    const filter = {}
61
    filter[this.key] = id
62
63
    return this.model
64
      .remove(filter)
65
      .then(() => {
66
        return {}
67
      })
68
  }
69
70
  /**
71
   */
72
  update(id, data) {
73
    var filter = {}
74
    filter[this.key] = id
75
76
    return this.model
77
      .findOne(filter)
78
      .then((modelInstance) => {
79
        for (var attribute in data) {
80
          if (data.hasOwnProperty(attribute) && attribute !== this.key && attribute !== '_id') {
81
            modelInstance[attribute] = data[attribute]
82
          }
83
        }
84
85
        return modelInstance.save()
86
      })
87
      .then((modelInstance) => {
88
        var response = {}
89
        response[this.modelName] = modelInstance
90
        return response
91
      })
92
  }
93
94
  routeAPI() {
95
    const router = new Router()
96
97
    router.get('/', (req, res) => {
98
      this
99
        .list()
100
        .then(ok(res))
101
        .then(null, fail(res))
102
    })
103
104
    router.post('/', (req, res) => {
105
      this
106
        .create(req.body)
107
        .then(ok(res))
108
        .then(null, fail(res))
109
    })
110
111
    router.get('/:key', (req, res) => {
112
      this
113
        .read(req.params.key)
114
        .then(ok(res))
115
        .then(null, fail(res))
116
    })
117
118
    router.put('/:key', (req, res) => {
119
      this
120
        .update(req.params.key, req.body)
121
        .then(ok(res))
122
        .then(null, fail(res))
123
    })
124
125
    router.delete('/:key', (req, res) => {
126
      this
127
        .delete(req.params.key)
128
        .then(ok(res))
129
        .then(null, fail(res))
130
    })
131
132
    return router
133
  }
134
135
  route() {
136
    const router = new Router()
137
138
    // Declare locals to use
139
    router.use((req, res, next) => {
140
      res.locals.moment = require('moment')
141
      next()
142
    })
143
144
    router.get('/', (req, res) => {
145
      this
146
        .list()
147
        .then((list) => {
148
          let pageResp = {
149
            title: this.model.modelName
150
          }
151
          const arr = []
152
          for (const obj of list[pluralize(this.modelName)]) {
153
            arr.push(obj.toObject())
154
          }
155
          pageResp[pluralize(this.modelName)] = arr
156
          respond(res, this.modelName + '/index', pageResp)
157
        })
158
        .then(null, fail(res))
159
    })
160
161
    router.get('/new', (req, res) => {
162
      res.render(this.modelName + '/new', { title: 'Add New ' + this.model.modelName });
163
    })
164
165
    router.post('/', (req, res) => {
166
      logger.info('Will create the object: ' + JSON.stringify(req.body))
0 ignored issues
show
Bug introduced by
The variable logger seems to be never declared. If this is a global, consider adding a /** global: logger */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
167
      this
168
        .create(req.body)
169
        .then(res.redirect('/' + pluralize(this.modelName)))
170
        .then(null, fail(res))
171
    })
172
173
    router.get('/:key', (req, res) => {
174
      this
175
        .read(req.params.key)
176
        .then(obj => {
177
          let pageResp = {
178
            title: this.model.modelName
179
          }
180
          pageResp[this.modelName] = obj[this.modelName].toObject()
181
          respond(res, this.modelName + '/show', pageResp)
182
        })
183
        .then(null, fail(res))
184
    })
185
186
187
    router.route('/:key/edit').get((req, res) => {
188
      this
189
        .read(req.params.key)
190
        .then((obj) => {
191
          let pageResp = {
192
            title: this.model.modelName
193
          }
194
          pageResp[this.modelName] = obj[this.modelName].toObject()
195
          respond(res, this.modelName + '/edit', pageResp)
196
        })
197
        .then(null, fail(res))
198
    }).delete((req, res) => {
199
      logger.info('Will delete the object: ' + req.body.key)
0 ignored issues
show
Bug introduced by
The variable logger seems to be never declared. If this is a global, consider adding a /** global: logger */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
200
      this
201
        .delete(req.body.key)
202
        .then(res.redirect('/' + pluralize(this.modelName)))
203
        .then(null, fail(res))
204
    }).put((req, res) => {
205
      logger.info('Will update the object: ' + req.params.id)
0 ignored issues
show
Bug introduced by
The variable logger seems to be never declared. If this is a global, consider adding a /** global: logger */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
206
      this
207
        .update(req.body.id, req.body)
208
        .then(res.redirect('/' + pluralize(this.modelName) + '/' + req.params.key))
209
        .then(null, fail(res))
210
    })
211
    // TODO PUT and DELETE for Edit opeation
212
213
    return router
214
  }
215
}
216