express-restify-mongoose 6.1.2 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +19 -19
  2. package/README.md +57 -52
  3. package/dist/buildQuery.js +44 -0
  4. package/dist/cjs/buildQuery.js +52 -0
  5. package/dist/cjs/detective.js +39 -0
  6. package/dist/cjs/errorHandler.js +20 -0
  7. package/dist/cjs/express-restify-mongoose.js +104 -0
  8. package/dist/cjs/getQuerySchema.js +161 -0
  9. package/dist/cjs/middleware/access.js +32 -0
  10. package/dist/cjs/middleware/ensureContentType.js +23 -0
  11. package/dist/cjs/middleware/filterAndFindById.js +32 -0
  12. package/dist/cjs/middleware/onError.js +29 -0
  13. package/dist/cjs/middleware/outputFn.js +26 -0
  14. package/dist/cjs/middleware/prepareOutput.js +89 -0
  15. package/dist/cjs/middleware/prepareQuery.js +25 -0
  16. package/dist/cjs/moredots.js +24 -0
  17. package/dist/cjs/operations.js +259 -0
  18. package/dist/cjs/resource_filter.js +113 -0
  19. package/dist/cjs/types.js +4 -0
  20. package/dist/cjs/weedout.js +27 -0
  21. package/dist/detective.js +31 -0
  22. package/dist/errorHandler.js +12 -0
  23. package/dist/express-restify-mongoose.d.ts +45 -0
  24. package/dist/express-restify-mongoose.js +96 -0
  25. package/dist/getQuerySchema.js +153 -0
  26. package/dist/middleware/access.js +24 -0
  27. package/dist/middleware/ensureContentType.js +15 -0
  28. package/dist/middleware/filterAndFindById.js +24 -0
  29. package/dist/middleware/onError.js +21 -0
  30. package/dist/middleware/outputFn.js +18 -0
  31. package/dist/middleware/prepareOutput.js +81 -0
  32. package/dist/middleware/prepareQuery.js +17 -0
  33. package/dist/moredots.js +11 -0
  34. package/dist/operations.js +246 -0
  35. package/dist/resource_filter.js +105 -0
  36. package/dist/types.js +1 -0
  37. package/dist/weedout.js +19 -0
  38. package/package.json +80 -85
  39. package/CHANGELOG.md +0 -92
  40. package/src/buildQuery.js +0 -55
  41. package/src/errorHandler.js +0 -17
  42. package/src/express-restify-mongoose.js +0 -144
  43. package/src/middleware/access.js +0 -26
  44. package/src/middleware/ensureContentType.js +0 -19
  45. package/src/middleware/filterAndFindById.js +0 -35
  46. package/src/middleware/onError.js +0 -26
  47. package/src/middleware/outputFn.js +0 -15
  48. package/src/middleware/prepareOutput.js +0 -75
  49. package/src/middleware/prepareQuery.js +0 -115
  50. package/src/operations.js +0 -274
  51. package/src/resource_filter.js +0 -192
package/src/buildQuery.js DELETED
@@ -1,55 +0,0 @@
1
- 'use strict'
2
-
3
- module.exports = function (options) {
4
- return function (query, queryOptions) {
5
- const promise = new Promise((resolve, reject) => {
6
- if (!queryOptions) {
7
- return resolve(query)
8
- }
9
-
10
- if (queryOptions.query) {
11
- query.where(queryOptions.query)
12
- }
13
-
14
- if (queryOptions.skip) {
15
- query.skip(queryOptions.skip)
16
- }
17
-
18
- if (options.limit && (!queryOptions.limit || queryOptions.limit === '0' || queryOptions.limit > options.limit)) {
19
- queryOptions.limit = options.limit
20
- }
21
-
22
- if (queryOptions.limit && query.op !== 'count' && !queryOptions.distinct) {
23
- query.limit(queryOptions.limit)
24
- }
25
-
26
- if (queryOptions.sort) {
27
- query.sort(queryOptions.sort)
28
- }
29
-
30
- if (queryOptions.populate) {
31
- query.populate(queryOptions.populate)
32
- }
33
-
34
- if (queryOptions.select) {
35
- query.select(queryOptions.select)
36
- }
37
-
38
- if (queryOptions.distinct) {
39
- query.distinct(queryOptions.distinct)
40
- }
41
-
42
- if (options.readPreference) {
43
- query.read(options.readPreference)
44
- }
45
-
46
- if (options.lean) {
47
- query.lean(options.lean)
48
- }
49
-
50
- resolve(query)
51
- })
52
-
53
- return promise
54
- }
55
- }
@@ -1,17 +0,0 @@
1
- 'use strict'
2
-
3
- const http = require('http')
4
-
5
- module.exports = function (options) {
6
- return function (req, res, next) {
7
- return function (err) {
8
- if (err.message === http.STATUS_CODES[404] || (req.params.id && err.path === options.idProperty && err.name === 'CastError')) {
9
- req.erm.statusCode = 404
10
- } else {
11
- req.erm.statusCode = req.erm.statusCode && req.erm.statusCode >= 400 ? req.erm.statusCode : 400
12
- }
13
-
14
- options.onError(err, req, res, next)
15
- }
16
- }
17
- }
@@ -1,144 +0,0 @@
1
- 'use strict'
2
-
3
- const defaults = require('lodash.defaults')
4
- const ensureArray = require('ensure-array')
5
- const util = require('util')
6
- const Filter = require('./resource_filter')
7
- let customDefaults = null
8
- const excludedMap = {}
9
-
10
- function getDefaults() {
11
- return defaults(Object.assign({}, customDefaults), {
12
- prefix: '/api',
13
- version: '/v1',
14
- idProperty: '_id',
15
- findOneAndUpdate: true,
16
- findOneAndRemove: true,
17
- lean: true,
18
- restify: false,
19
- runValidators: false,
20
- allowRegex: true,
21
- private: [],
22
- protected: [],
23
- upsert: false,
24
- })
25
- }
26
-
27
- const restify = function (app, model, opts) {
28
- const options = Object.assign({}, getDefaults(), opts || {})
29
-
30
- const access = require('./middleware/access')
31
- const ensureContentType = require('./middleware/ensureContentType')(options)
32
- const filterAndFindById = require('./middleware/filterAndFindById')(model, options)
33
- const onError = require('./middleware/onError')
34
- const outputFn = require('./middleware/outputFn')
35
- const prepareQuery = require('./middleware/prepareQuery')(options)
36
- const prepareOutput = require('./middleware/prepareOutput')(options, excludedMap)
37
-
38
- if (!Array.isArray(options.private)) {
39
- throw new Error('"options.private" must be an array of fields')
40
- }
41
-
42
- if (!Array.isArray(options.protected)) {
43
- throw new Error('"options.protected" must be an array of fields')
44
- }
45
-
46
- model.schema.eachPath((name, path) => {
47
- if (path.options.access) {
48
- switch (path.options.access.toLowerCase()) {
49
- case 'private':
50
- options.private.push(name)
51
- break
52
- case 'protected':
53
- options.protected.push(name)
54
- break
55
- }
56
- }
57
- })
58
-
59
- options.filter = new Filter({
60
- model,
61
- excludedMap,
62
- filteredKeys: {
63
- private: options.private,
64
- protected: options.protected,
65
- },
66
- })
67
-
68
- excludedMap[model.modelName] = options.filter.filteredKeys
69
-
70
- options.preMiddleware = ensureArray(options.preMiddleware)
71
- options.preCreate = ensureArray(options.preCreate)
72
- options.preRead = ensureArray(options.preRead)
73
- options.preUpdate = ensureArray(options.preUpdate)
74
- options.preDelete = ensureArray(options.preDelete)
75
-
76
- if (!options.contextFilter) {
77
- options.contextFilter = (model, req, done) => done(model)
78
- }
79
-
80
- options.postCreate = ensureArray(options.postCreate)
81
- options.postRead = ensureArray(options.postRead)
82
- options.postUpdate = ensureArray(options.postUpdate)
83
- options.postDelete = ensureArray(options.postDelete)
84
-
85
- if (!options.onError) {
86
- options.onError = onError(!options.restify)
87
- }
88
-
89
- if (!options.outputFn) {
90
- options.outputFn = outputFn(!options.restify)
91
- }
92
-
93
- options.name = options.name || model.modelName
94
-
95
- const ops = require('./operations')(model, options, excludedMap)
96
-
97
- let uriItem = `${options.prefix}${options.version}/${options.name}`
98
- if (uriItem.indexOf('/:id') === -1) {
99
- uriItem += '/:id'
100
- }
101
-
102
- const uriItems = uriItem.replace('/:id', '')
103
- const uriCount = uriItems + '/count'
104
- const uriShallow = uriItem + '/shallow'
105
-
106
- if (typeof app.delete === 'undefined') {
107
- app.delete = app.del
108
- }
109
-
110
- app.use((req, res, next) => {
111
- const getModel = options.modelFactory && options.modelFactory.getModel
112
-
113
- req.erm = {
114
- model: typeof getModel === 'function' ? getModel() : model,
115
- }
116
-
117
- next()
118
- })
119
-
120
- const accessMiddleware = options.access ? access(options) : []
121
-
122
- app.get(uriItems, prepareQuery, options.preMiddleware, options.preRead, accessMiddleware, ops.getItems, prepareOutput)
123
- app.get(uriCount, prepareQuery, options.preMiddleware, options.preRead, accessMiddleware, ops.getCount, prepareOutput)
124
- app.get(uriItem, prepareQuery, options.preMiddleware, options.preRead, accessMiddleware, ops.getItem, prepareOutput)
125
- app.get(uriShallow, prepareQuery, options.preMiddleware, options.preRead, accessMiddleware, ops.getShallow, prepareOutput)
126
-
127
- app.post(uriItems, prepareQuery, ensureContentType, options.preMiddleware, options.preCreate, accessMiddleware, ops.createObject, prepareOutput)
128
- app.post(uriItem, util.deprecate(prepareQuery, 'express-restify-mongoose: in a future major version, the POST method to update resources will be removed. Use PATCH instead.'), ensureContentType, options.preMiddleware, options.findOneAndUpdate ? [] : filterAndFindById, options.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput)
129
-
130
- app.put(uriItem, util.deprecate(prepareQuery, 'express-restify-mongoose: in a future major version, the PUT method will replace rather than update a resource. Use PATCH instead.'), ensureContentType, options.preMiddleware, options.findOneAndUpdate ? [] : filterAndFindById, options.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput)
131
- app.patch(uriItem, prepareQuery, ensureContentType, options.preMiddleware, options.findOneAndUpdate ? [] : filterAndFindById, options.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput)
132
-
133
- app.delete(uriItems, prepareQuery, options.preMiddleware, options.preDelete, ops.deleteItems, prepareOutput)
134
- app.delete(uriItem, prepareQuery, options.preMiddleware, options.findOneAndRemove ? [] : filterAndFindById, options.preDelete, ops.deleteItem, prepareOutput)
135
-
136
- return uriItems
137
- }
138
-
139
- module.exports = {
140
- defaults: function (options) {
141
- customDefaults = options
142
- },
143
- serve: restify,
144
- }
@@ -1,26 +0,0 @@
1
- 'use strict'
2
-
3
- module.exports = function (options) {
4
- const errorHandler = require('../errorHandler')(options)
5
-
6
- return function (req, res, next) {
7
- const handler = function (err, access) {
8
- if (err) {
9
- return errorHandler(req, res, next)(err)
10
- }
11
-
12
- if (['public', 'private', 'protected'].indexOf(access) < 0) {
13
- throw new Error('Unsupported access, must be "private", "protected" or "public"')
14
- }
15
-
16
- req.access = access
17
- next()
18
- }
19
-
20
- if (options.access.length > 1) {
21
- options.access(req, handler)
22
- } else {
23
- handler(null, options.access(req))
24
- }
25
- }
26
- }
@@ -1,19 +0,0 @@
1
- 'use strict'
2
-
3
- module.exports = function (options) {
4
- const errorHandler = require('../errorHandler')(options)
5
-
6
- return function ensureContentType(req, res, next) {
7
- const ct = req.headers['content-type']
8
-
9
- if (!ct) {
10
- return errorHandler(req, res, next)(new Error('missing_content_type'))
11
- }
12
-
13
- if (ct.indexOf('application/json') === -1) {
14
- return errorHandler(req, res, next)(new Error('invalid_content_type'))
15
- }
16
-
17
- next()
18
- }
19
- }
@@ -1,35 +0,0 @@
1
- 'use strict'
2
-
3
- const http = require('http')
4
-
5
- module.exports = function (model, options) {
6
- const errorHandler = require('../errorHandler')(options)
7
-
8
- return function (req, res, next) {
9
- const contextModel = (req.erm && req.erm.model) || model
10
-
11
- if (!req.params.id) {
12
- return next()
13
- }
14
-
15
- options.contextFilter(contextModel, req, (filteredContext) => {
16
- filteredContext
17
- .findOne()
18
- .and({
19
- [options.idProperty]: req.params.id,
20
- })
21
- .lean(false)
22
- .read(options.readPreference || 'p')
23
- .exec()
24
- .then((doc) => {
25
- if (!doc) {
26
- return errorHandler(req, res, next)(new Error(http.STATUS_CODES[404]))
27
- }
28
-
29
- req.erm.document = doc
30
-
31
- next()
32
- }, errorHandler(req, res, next))
33
- })
34
- }
35
- }
@@ -1,26 +0,0 @@
1
- 'use strict'
2
-
3
- const { serializeError } = require('serialize-error')
4
-
5
- module.exports = function (isExpress) {
6
- return function (err, req, res, next) {
7
- const serializedErr = serializeError(err)
8
-
9
- delete serializedErr.stack
10
-
11
- if (serializedErr.errors) {
12
- for (const key in serializedErr.errors) {
13
- delete serializedErr.errors[key].reason
14
- delete serializedErr.errors[key].stack
15
- }
16
- }
17
-
18
- res.setHeader('Content-Type', 'application/json')
19
-
20
- if (isExpress) {
21
- res.status(req.erm.statusCode).send(serializedErr)
22
- } else {
23
- res.send(req.erm.statusCode, serializedErr)
24
- }
25
- }
26
- }
@@ -1,15 +0,0 @@
1
- 'use strict'
2
-
3
- module.exports = function (isExpress) {
4
- return function output(req, res) {
5
- if (isExpress) {
6
- if (req.erm.result) {
7
- res.status(req.erm.statusCode).json(req.erm.result)
8
- } else {
9
- res.sendStatus(req.erm.statusCode)
10
- }
11
- } else {
12
- res.send(req.erm.statusCode, req.erm.result)
13
- }
14
- }
15
- }
@@ -1,75 +0,0 @@
1
- 'use strict'
2
-
3
- const runSeries = require('run-series')
4
-
5
- module.exports = function (options, excludedMap) {
6
- const errorHandler = require('../errorHandler')(options)
7
-
8
- return function (req, res, next) {
9
- const postMiddleware = (() => {
10
- switch (req.method.toLowerCase()) {
11
- case 'get':
12
- return options.postRead
13
- case 'post':
14
- if (req.erm.statusCode === 201) {
15
- return options.postCreate
16
- }
17
-
18
- return options.postUpdate
19
- case 'put':
20
- case 'patch':
21
- return options.postUpdate
22
- case 'delete':
23
- return options.postDelete
24
- }
25
- })()
26
-
27
- const callback = (err) => {
28
- if (err) {
29
- return errorHandler(req, res, next)(err)
30
- }
31
-
32
- // TODO: this will, but should not, filter /count queries
33
- if (req.erm.result) {
34
- const opts = {
35
- access: req.access,
36
- excludedMap: excludedMap,
37
- populate: req.erm && req.erm.query ? req.erm.query.populate : null,
38
- }
39
-
40
- req.erm.result = options.filter ? options.filter.filterObject(req.erm.result, opts) : req.erm.result
41
- }
42
-
43
- if (options.totalCountHeader && req.erm.totalCount !== 'undefined') {
44
- res.header(typeof options.totalCountHeader === 'string' ? options.totalCountHeader : 'X-Total-Count', req.erm.totalCount)
45
- }
46
-
47
- const promise = options.outputFn(req, res)
48
-
49
- if (options.postProcess) {
50
- if (promise && typeof promise.then === 'function') {
51
- promise
52
- .then(() => {
53
- options.postProcess(req, res)
54
- })
55
- .catch(errorHandler(req, res, next))
56
- } else {
57
- options.postProcess(req, res)
58
- }
59
- }
60
- }
61
-
62
- if (!postMiddleware || postMiddleware.length === 0) {
63
- return callback()
64
- }
65
-
66
- runSeries(
67
- postMiddleware.map((middleware, i) => {
68
- return (cb) => {
69
- middleware(req, res, cb)
70
- }
71
- }),
72
- callback
73
- )
74
- }
75
- }
@@ -1,115 +0,0 @@
1
- 'use strict'
2
-
3
- const isCoordinates = require('is-coordinates')
4
-
5
- module.exports = function (options) {
6
- const errorHandler = require('../errorHandler')(options)
7
-
8
- function jsonQueryParser(key, value) {
9
- if (key === '$regex' && !options.allowRegex) {
10
- return undefined
11
- }
12
-
13
- if (Array.isArray(value) && key[0] !== '$' && key !== 'coordinates' && !isCoordinates(value)) {
14
- return { $in: value }
15
- }
16
-
17
- return value
18
- }
19
-
20
- function parseQueryOptions(queryOptions) {
21
- if (queryOptions.select && typeof queryOptions.select === 'string') {
22
- const select = queryOptions.select.split(',')
23
- queryOptions.select = {}
24
-
25
- for (let i = 0, length = select.length; i < length; i++) {
26
- if (select[i][0] === '-') {
27
- queryOptions.select[select[i].substring(1)] = 0
28
- } else {
29
- queryOptions.select[select[i]] = 1
30
- }
31
- }
32
- }
33
-
34
- if (queryOptions.populate) {
35
- if (typeof queryOptions.populate === 'string') {
36
- const populate = queryOptions.populate.split(',')
37
- queryOptions.populate = []
38
-
39
- for (let i = 0, length = populate.length; i < length; i++) {
40
- queryOptions.populate.push({
41
- path: populate[i],
42
- })
43
-
44
- for (const key in queryOptions.select) {
45
- if (key.indexOf(populate[i] + '.') === 0) {
46
- if (queryOptions.populate[i].select) {
47
- queryOptions.populate[i].select += ' '
48
- } else {
49
- queryOptions.populate[i].select = ''
50
- }
51
-
52
- if (queryOptions.select[key] === 0) {
53
- queryOptions.populate[i].select += '-'
54
- }
55
-
56
- queryOptions.populate[i].select += key.substring(populate[i].length + 1)
57
- delete queryOptions.select[key]
58
- }
59
- }
60
-
61
- // If other specific fields are selected, add the populated field
62
- if (queryOptions.select) {
63
- if (Object.keys(queryOptions.select).length > 0 && !queryOptions.select[populate[i]]) {
64
- queryOptions.select[populate[i]] = 1
65
- } else if (Object.keys(queryOptions.select).length === 0) {
66
- delete queryOptions.select
67
- }
68
- }
69
- }
70
- } else if (!Array.isArray(queryOptions.populate)) {
71
- queryOptions.populate = [queryOptions.populate]
72
- }
73
- }
74
-
75
- return queryOptions
76
- }
77
-
78
- return function (req, res, next) {
79
- const whitelist = ['distinct', 'limit', 'populate', 'query', 'select', 'skip', 'sort']
80
- const query = {}
81
-
82
- for (const key in req.query) {
83
- if (whitelist.indexOf(key) === -1) {
84
- continue
85
- }
86
-
87
- if (key === 'query') {
88
- try {
89
- query[key] = JSON.parse(req.query[key], jsonQueryParser)
90
- } catch (e) {
91
- return errorHandler(req, res, next)(new Error(`invalid_json_${key}`))
92
- }
93
- } else if (key === 'populate' || key === 'select' || key === 'sort') {
94
- try {
95
- query[key] = JSON.parse(req.query[key])
96
- } catch (e) {
97
- query[key] = req.query[key]
98
- }
99
- } else if (key === 'limit' || key === 'skip') {
100
- query[key] = parseInt(req.query[key], 10)
101
-
102
- if (`${query[key]}` !== `${req.query[key]}`) {
103
- return errorHandler(req, res, next)(new Error(`invalid_${key}_value`))
104
- }
105
- } else {
106
- query[key] = req.query[key]
107
- }
108
- }
109
-
110
- req.erm = req.erm || {}
111
- req.erm.query = parseQueryOptions(query)
112
-
113
- next()
114
- }
115
- }