express-restify-mongoose 7.0.2 β†’ 9.0.1

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.
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getPrepareOutputHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getPrepareOutputHandler;
9
+ }
10
+ });
11
+ const _errorHandler = require("../errorHandler.js");
12
+ function isDefined(arg) {
13
+ return typeof arg !== "undefined";
14
+ }
15
+ function getPrepareOutputHandler(options, modelName, filter) {
16
+ const errorHandler = (0, _errorHandler.getErrorHandler)(options);
17
+ const fn = function prepareOutput(req, res, next) {
18
+ const postMiddleware = (()=>{
19
+ switch(req.method.toLowerCase()){
20
+ case "get":
21
+ {
22
+ return Array.isArray(options.postRead) ? options.postRead : [
23
+ options.postRead
24
+ ];
25
+ }
26
+ case "post":
27
+ {
28
+ if (req.erm.statusCode === 201) {
29
+ return Array.isArray(options.postCreate) ? options.postCreate : [
30
+ options.postCreate
31
+ ];
32
+ }
33
+ return Array.isArray(options.postUpdate) ? options.postUpdate : [
34
+ options.postUpdate
35
+ ];
36
+ }
37
+ case "put":
38
+ case "patch":
39
+ {
40
+ return Array.isArray(options.postUpdate) ? options.postUpdate : [
41
+ options.postUpdate
42
+ ];
43
+ }
44
+ case "delete":
45
+ {
46
+ return Array.isArray(options.postDelete) ? options.postDelete : [
47
+ options.postDelete
48
+ ];
49
+ }
50
+ default:
51
+ {
52
+ return [];
53
+ }
54
+ }
55
+ })().filter(isDefined);
56
+ const callback = ()=>{
57
+ // TODO: this will, but should not, filter /count queries
58
+ if (req.erm.result) {
59
+ req.erm.result = filter.filterObject(req.erm.result, {
60
+ access: req.access,
61
+ modelName,
62
+ // @ts-expect-error this is fine 🐢πŸ”₯
63
+ populate: req.erm.query?.populate
64
+ });
65
+ }
66
+ if (options.totalCountHeader && typeof req.erm.totalCount === "number") {
67
+ res.header(typeof options.totalCountHeader === "string" ? options.totalCountHeader : "X-Total-Count", `${req.erm.totalCount}`);
68
+ }
69
+ const promise = options.outputFn(req, res);
70
+ if (options.postProcess) {
71
+ if (promise && typeof promise.then === "function") {
72
+ promise.then(()=>{
73
+ options.postProcess?.(req, res);
74
+ }).catch((err)=>errorHandler(err, req, res, next));
75
+ } else {
76
+ options.postProcess(req, res);
77
+ }
78
+ }
79
+ };
80
+ if (!postMiddleware || postMiddleware.length === 0) {
81
+ return callback();
82
+ }
83
+ postMiddleware.reduce(async (acc, middleware)=>{
84
+ await acc;
85
+ return new Promise((resolve, reject)=>{
86
+ middleware(req, res, (err)=>err ? reject(err) : resolve(err));
87
+ });
88
+ }, Promise.resolve()).then(callback).catch((err)=>errorHandler(err, req, res, next));
89
+ };
90
+ return fn;
91
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getPrepareQueryHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getPrepareQueryHandler;
9
+ }
10
+ });
11
+ const _errorHandler = require("../errorHandler.js");
12
+ const _getQuerySchema = require("../getQuerySchema.js");
13
+ function getPrepareQueryHandler(options) {
14
+ const errorHandler = (0, _errorHandler.getErrorHandler)(options);
15
+ const fn = function prepareQuery(req, res, next) {
16
+ req.erm = req.erm || {};
17
+ try {
18
+ req.erm.query = (0, _getQuerySchema.getQueryOptionsSchema)({
19
+ allowRegex: options.allowRegex
20
+ }).parse(req.query || {});
21
+ next();
22
+ } catch (e) {
23
+ return errorHandler(new Error("invalid_json_query"), req, res, next);
24
+ }
25
+ };
26
+ return fn;
27
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "moredots", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return moredots;
9
+ }
10
+ });
11
+ const _lodashisplainobject = /*#__PURE__*/ _interop_require_default(require("lodash.isplainobject"));
12
+ function _interop_require_default(obj) {
13
+ return obj && obj.__esModule ? obj : {
14
+ default: obj
15
+ };
16
+ }
17
+ function moredots(src, dst = {}, prefix = "") {
18
+ for (const [key, value] of Object.entries(src)){
19
+ if ((0, _lodashisplainobject.default)(value)) {
20
+ moredots(value, dst, `${prefix}${key}.`);
21
+ } else {
22
+ dst[`${prefix}${key}`] = value;
23
+ }
24
+ }
25
+ return dst;
26
+ }
@@ -0,0 +1,265 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "operations", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return operations;
9
+ }
10
+ });
11
+ const _http = require("http");
12
+ const _lodashisplainobject = /*#__PURE__*/ _interop_require_default(require("lodash.isplainobject"));
13
+ const _buildQuery = require("./buildQuery.js");
14
+ const _errorHandler = require("./errorHandler.js");
15
+ const _moredots = require("./moredots.js");
16
+ function _interop_require_default(obj) {
17
+ return obj && obj.__esModule ? obj : {
18
+ default: obj
19
+ };
20
+ }
21
+ function operations(model, options, filter) {
22
+ const buildQuery = (0, _buildQuery.getBuildQuery)(options);
23
+ const errorHandler = (0, _errorHandler.getErrorHandler)(options);
24
+ function findById(filteredContext, id) {
25
+ return filteredContext.findOne().and([
26
+ {
27
+ [options.idProperty]: id
28
+ }
29
+ ]);
30
+ }
31
+ function isDistinctExcluded(req) {
32
+ if (!req.erm.query?.distinct) {
33
+ return false;
34
+ }
35
+ return filter.getExcluded({
36
+ access: req.access,
37
+ modelName: model.modelName
38
+ }).includes(req.erm.query.distinct);
39
+ }
40
+ const getItems = function(req, res, next) {
41
+ const contextModel = model;
42
+ if (isDistinctExcluded(req)) {
43
+ req.erm.result = [];
44
+ req.erm.statusCode = 200;
45
+ return next();
46
+ }
47
+ options.contextFilter(contextModel, req, (filteredContext)=>{
48
+ buildQuery(// @ts-expect-error this is fine 🐢πŸ”₯
49
+ filteredContext.find(), req.erm.query).then((items)=>{
50
+ req.erm.result = items;
51
+ req.erm.statusCode = 200;
52
+ if (options.totalCountHeader && !req.erm.query?.distinct) {
53
+ options.contextFilter(contextModel, req, (countFilteredContext)=>{
54
+ buildQuery(countFilteredContext.countDocuments(), {
55
+ ...req.erm.query,
56
+ skip: 0,
57
+ limit: 0
58
+ }).then((count)=>{
59
+ req.erm.totalCount = count;
60
+ next();
61
+ }).catch((err)=>errorHandler(err, req, res, next));
62
+ });
63
+ } else {
64
+ next();
65
+ }
66
+ }).catch((err)=>errorHandler(err, req, res, next));
67
+ });
68
+ };
69
+ const getCount = function(req, res, next) {
70
+ const contextModel = model;
71
+ options.contextFilter(contextModel, req, (filteredContext)=>{
72
+ buildQuery(filteredContext.countDocuments(), req.erm.query).then((count)=>{
73
+ req.erm.result = {
74
+ count: count
75
+ };
76
+ req.erm.statusCode = 200;
77
+ next();
78
+ }).catch((err)=>errorHandler(err, req, res, next));
79
+ });
80
+ };
81
+ const getShallow = function(req, res, next) {
82
+ const contextModel = model;
83
+ options.contextFilter(contextModel, req, (filteredContext)=>{
84
+ buildQuery(// @ts-expect-error this is fine 🐢πŸ”₯
85
+ findById(filteredContext, req.params.id), req.erm.query).then((item)=>{
86
+ if (!item) {
87
+ return errorHandler(new Error(_http.STATUS_CODES[404]), req, res, next);
88
+ }
89
+ for(const prop in item){
90
+ item[prop] = typeof item[prop] === "object" && prop !== "_id" ? true : item[prop];
91
+ }
92
+ req.erm.result = item;
93
+ req.erm.statusCode = 200;
94
+ next();
95
+ }).catch((err)=>errorHandler(err, req, res, next));
96
+ });
97
+ };
98
+ const deleteItems = function(req, res, next) {
99
+ const contextModel = model;
100
+ options.contextFilter(contextModel, req, (filteredContext)=>{
101
+ buildQuery(filteredContext.deleteMany(), req.erm.query).then(()=>{
102
+ req.erm.statusCode = 204;
103
+ next();
104
+ }).catch((err)=>errorHandler(err, req, res, next));
105
+ });
106
+ };
107
+ const getItem = function(req, res, next) {
108
+ const contextModel = model;
109
+ if (isDistinctExcluded(req)) {
110
+ req.erm.result = [];
111
+ req.erm.statusCode = 200;
112
+ return next();
113
+ }
114
+ options.contextFilter(contextModel, req, (filteredContext)=>{
115
+ buildQuery(// @ts-expect-error this is fine 🐢πŸ”₯
116
+ findById(filteredContext, req.params.id), req.erm.query).then((item)=>{
117
+ if (!item) {
118
+ return errorHandler(new Error(_http.STATUS_CODES[404]), req, res, next);
119
+ }
120
+ req.erm.result = item;
121
+ req.erm.statusCode = 200;
122
+ next();
123
+ }).catch((err)=>errorHandler(err, req, res, next));
124
+ });
125
+ };
126
+ const deleteItem = function(req, res, next) {
127
+ const contextModel = model;
128
+ if (options.findOneAndRemove) {
129
+ options.contextFilter(contextModel, req, (filteredContext)=>{
130
+ // @ts-expect-error this is fine 🐢πŸ”₯
131
+ findById(filteredContext, req.params.id).findOneAndDelete() // switched to findOneAndDelete to add support for Mongoose 7 and 8
132
+ .then((item)=>{
133
+ if (!item) {
134
+ return errorHandler(new Error(_http.STATUS_CODES[404]), req, res, next);
135
+ }
136
+ req.erm.statusCode = 204;
137
+ next();
138
+ }).catch((err)=>errorHandler(err, req, res, next));
139
+ });
140
+ } else {
141
+ req.erm.document?.deleteOne() // switched to deleteOne to add support for Mongoose 7 and 8
142
+ .then(()=>{
143
+ req.erm.statusCode = 204;
144
+ next();
145
+ }).catch((err)=>errorHandler(err, req, res, next));
146
+ }
147
+ };
148
+ const createObject = function(req, res, next) {
149
+ const contextModel = model;
150
+ req.body = filter.filterObject(req.body || {}, {
151
+ access: req.access,
152
+ modelName: model.modelName,
153
+ // @ts-expect-error this is fine 🐢πŸ”₯
154
+ populate: req.erm.query?.populate
155
+ });
156
+ if (req.body._id === null) {
157
+ delete req.body._id;
158
+ }
159
+ // @ts-expect-error this is fine 🐢πŸ”₯
160
+ if (contextModel.schema.options.versionKey) {
161
+ // @ts-expect-error this is fine 🐢πŸ”₯
162
+ delete req.body[contextModel.schema.options.versionKey];
163
+ }
164
+ contextModel.create(req.body).then((item)=>{
165
+ // @ts-expect-error this is fine 🐢πŸ”₯
166
+ return contextModel.populate(item, req.erm.query?.populate || []);
167
+ }).then((item)=>{
168
+ req.erm.result = item;
169
+ req.erm.statusCode = 201;
170
+ next();
171
+ }).catch((err)=>errorHandler(err, req, res, next));
172
+ };
173
+ const modifyObject = function(req, res, next) {
174
+ const contextModel = model;
175
+ req.body = filter.filterObject(req.body || {}, {
176
+ access: req.access,
177
+ modelName: model.modelName,
178
+ // @ts-expect-error this is fine 🐢πŸ”₯
179
+ populate: req.erm.query?.populate
180
+ });
181
+ delete req.body._id;
182
+ // @ts-expect-error this is fine 🐢πŸ”₯
183
+ if (contextModel.schema.options.versionKey) {
184
+ // @ts-expect-error this is fine 🐢πŸ”₯
185
+ delete req.body[contextModel.schema.options.versionKey];
186
+ }
187
+ function depopulate(src) {
188
+ const dst = {};
189
+ for (const [key, value] of Object.entries(src)){
190
+ const path = contextModel.schema.path(key);
191
+ // @ts-expect-error this is fine 🐢πŸ”₯
192
+ // Add support for Mongoose 7 and 8 while keeping backwards-compatibility to 6 by allowing ObjectID and ObejctId
193
+ if (path && path.caster && (path.caster.instance === "ObjectID" || path.caster.instance === "ObjectId")) {
194
+ if (Array.isArray(value)) {
195
+ for(let j = 0; j < value.length; ++j){
196
+ if (typeof value[j] === "object") {
197
+ dst[key] = dst[key] || [];
198
+ // @ts-expect-error this is fine 🐢πŸ”₯
199
+ dst[key].push(value[j]._id);
200
+ }
201
+ }
202
+ } else if ((0, _lodashisplainobject.default)(value)) {
203
+ dst[key] = value._id;
204
+ }
205
+ } else if ((0, _lodashisplainobject.default)(value)) {
206
+ // Add support for Mongoose 7 and 8 while keeping backwards-compatibility to 6 by allowing ObjectID and ObejctId
207
+ if (path && (path.instance === "ObjectID" || path.instance === "ObjectId")) {
208
+ dst[key] = value._id;
209
+ } else {
210
+ dst[key] = depopulate(value);
211
+ }
212
+ }
213
+ if (typeof dst[key] === "undefined") {
214
+ dst[key] = value;
215
+ }
216
+ }
217
+ return dst;
218
+ }
219
+ const cleanBody = (0, _moredots.moredots)(depopulate(req.body));
220
+ if (options.findOneAndUpdate) {
221
+ options.contextFilter(contextModel, req, (filteredContext)=>{
222
+ // @ts-expect-error this is fine 🐢πŸ”₯
223
+ findById(filteredContext, req.params.id).findOneAndUpdate({}, {
224
+ $set: cleanBody
225
+ }, {
226
+ new: true,
227
+ upsert: options.upsert,
228
+ runValidators: options.runValidators
229
+ }).exec().then((item)=>{
230
+ // @ts-expect-error this is fine 🐢πŸ”₯
231
+ return contextModel.populate(item, req.erm.query?.populate || []);
232
+ }).then((item)=>{
233
+ if (!item) {
234
+ return errorHandler(new Error(_http.STATUS_CODES[404]), req, res, next);
235
+ }
236
+ req.erm.result = item;
237
+ req.erm.statusCode = 200;
238
+ next();
239
+ }).catch((err)=>errorHandler(err, req, res, next));
240
+ });
241
+ } else {
242
+ for (const [key, value] of Object.entries(cleanBody)){
243
+ req.erm.document?.set(key, value);
244
+ }
245
+ req.erm.document?.save().then((item)=>{
246
+ // @ts-expect-error this is fine 🐢πŸ”₯
247
+ return contextModel.populate(item, req.erm.query?.populate || []);
248
+ }).then((item)=>{
249
+ req.erm.result = item;
250
+ req.erm.statusCode = 200;
251
+ next();
252
+ }).catch((err)=>errorHandler(err, req, res, next));
253
+ }
254
+ };
255
+ return {
256
+ getItems,
257
+ getCount,
258
+ getItem,
259
+ getShallow,
260
+ createObject,
261
+ modifyObject,
262
+ deleteItems,
263
+ deleteItem
264
+ };
265
+ }
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "Filter", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return Filter;
9
+ }
10
+ });
11
+ const _dotprop = /*#__PURE__*/ _interop_require_default(require("dot-prop"));
12
+ const _detective = require("./detective.js");
13
+ const _weedout = require("./weedout.js");
14
+ function _define_property(obj, key, value) {
15
+ if (key in obj) {
16
+ Object.defineProperty(obj, key, {
17
+ value: value,
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true
21
+ });
22
+ } else {
23
+ obj[key] = value;
24
+ }
25
+ return obj;
26
+ }
27
+ function _interop_require_default(obj) {
28
+ return obj && obj.__esModule ? obj : {
29
+ default: obj
30
+ };
31
+ }
32
+ const { get: getProperty, has: hasProperty } = _dotprop.default; // Because we're using an older version of dotProp that supports CommonJS
33
+ class Filter {
34
+ add(model, options) {
35
+ if (model.discriminators) {
36
+ for(const modelName in model.discriminators){
37
+ const excluded = this.excludedMap.get(modelName);
38
+ if (excluded) {
39
+ options.filteredKeys.private = options.filteredKeys.private.concat(excluded.filteredKeys.private);
40
+ options.filteredKeys.protected = options.filteredKeys.protected.concat(excluded.filteredKeys.protected);
41
+ }
42
+ }
43
+ }
44
+ this.excludedMap.set(model.modelName, {
45
+ filteredKeys: options.filteredKeys,
46
+ model
47
+ });
48
+ }
49
+ /**
50
+ * Gets excluded keys for a given model and access.
51
+ */ getExcluded(options) {
52
+ if (options.access === "private") {
53
+ return [];
54
+ }
55
+ const filteredKeys = this.excludedMap.get(options.modelName)?.filteredKeys;
56
+ if (!filteredKeys) {
57
+ return [];
58
+ }
59
+ return options.access === "protected" ? filteredKeys.private : filteredKeys.private.concat(filteredKeys.protected);
60
+ }
61
+ /**
62
+ * Removes excluded keys from a document.
63
+ */ filterItem(item, excluded) {
64
+ if (!item) {
65
+ return item;
66
+ }
67
+ if (Array.isArray(item)) {
68
+ return item.map((i)=>this.filterItem(i, excluded));
69
+ }
70
+ if (excluded) {
71
+ if (typeof item.toObject === "function") {
72
+ item = item.toObject();
73
+ }
74
+ for(let i = 0; i < excluded.length; i++){
75
+ (0, _weedout.weedout)(item, excluded[i]);
76
+ }
77
+ }
78
+ return item;
79
+ }
80
+ /**
81
+ * Removes excluded keys from a document with populated subdocuments.
82
+ */ filterPopulatedItem(item, options) {
83
+ if (Array.isArray(item)) {
84
+ return item.map((i)=>this.filterPopulatedItem(i, options));
85
+ }
86
+ for(let i = 0; i < options.populate.length; i++){
87
+ if (!options.populate[i].path) {
88
+ continue;
89
+ }
90
+ const model = this.excludedMap.get(options.modelName)?.model;
91
+ if (!model) {
92
+ continue;
93
+ }
94
+ const excluded = this.getExcluded({
95
+ access: options.access,
96
+ modelName: (0, _detective.detective)(model, options.populate[i].path)
97
+ });
98
+ if (hasProperty(item, options.populate[i].path)) {
99
+ this.filterItem(getProperty(item, options.populate[i].path), excluded);
100
+ } else {
101
+ const pathToArray = options.populate[i].path.split(".").slice(0, -1).join(".");
102
+ if (hasProperty(item, pathToArray)) {
103
+ const array = getProperty(item, pathToArray);
104
+ const pathToObject = options.populate[i].path.split(".").slice(-1).join(".");
105
+ if (Array.isArray(array)) {
106
+ this.filterItem(// @ts-expect-error this is fine 🐢πŸ”₯
107
+ array.map((element)=>getProperty(element, pathToObject)), excluded);
108
+ }
109
+ }
110
+ }
111
+ }
112
+ return item;
113
+ }
114
+ /**
115
+ * Removes excluded keys from a document.
116
+ */ filterObject(resource, options) {
117
+ const excluded = this.getExcluded({
118
+ access: options.access,
119
+ modelName: options.modelName
120
+ });
121
+ const filtered = this.filterItem(resource, excluded);
122
+ if (options?.populate) {
123
+ this.filterPopulatedItem(filtered, {
124
+ access: options.access,
125
+ modelName: options.modelName,
126
+ populate: options.populate
127
+ });
128
+ }
129
+ return filtered;
130
+ }
131
+ constructor(){
132
+ _define_property(this, "excludedMap", new Map());
133
+ }
134
+ }
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "weedout", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return weedout;
9
+ }
10
+ });
11
+ function weedout(obj, path) {
12
+ const keys = path.split(".");
13
+ for(let i = 0, length = keys.length; i < length; i++){
14
+ if (Array.isArray(obj)) {
15
+ for(let j = 0; j < obj.length; j++){
16
+ weedout(obj[j], keys.slice(1).join("."));
17
+ }
18
+ } else if (!obj || typeof obj[keys[i]] === "undefined") {
19
+ return;
20
+ }
21
+ if (i < keys.length - 1) {
22
+ // @ts-expect-error this is fine 🐢πŸ”₯
23
+ obj = obj[keys[i]];
24
+ } else {
25
+ delete obj[keys[i]];
26
+ }
27
+ }
28
+ return obj;
29
+ }