express-restify-mongoose 7.0.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/README.md +0 -2
  2. package/dist/buildQuery.js +44 -0
  3. package/dist/cjs/buildQuery.js +52 -0
  4. package/dist/cjs/detective.js +39 -0
  5. package/dist/cjs/errorHandler.js +20 -0
  6. package/dist/cjs/express-restify-mongoose.js +104 -0
  7. package/dist/cjs/getQuerySchema.js +161 -0
  8. package/dist/cjs/middleware/access.js +32 -0
  9. package/dist/cjs/middleware/ensureContentType.js +23 -0
  10. package/dist/cjs/middleware/filterAndFindById.js +32 -0
  11. package/dist/cjs/middleware/onError.js +29 -0
  12. package/dist/cjs/middleware/outputFn.js +26 -0
  13. package/dist/cjs/middleware/prepareOutput.js +89 -0
  14. package/dist/cjs/middleware/prepareQuery.js +25 -0
  15. package/dist/cjs/moredots.js +24 -0
  16. package/dist/cjs/operations.js +259 -0
  17. package/dist/cjs/resource_filter.js +113 -0
  18. package/dist/cjs/types.js +4 -0
  19. package/dist/cjs/weedout.js +27 -0
  20. package/dist/detective.js +31 -0
  21. package/dist/errorHandler.js +12 -0
  22. package/dist/express-restify-mongoose.d.ts +45 -0
  23. package/dist/express-restify-mongoose.js +96 -0
  24. package/dist/getQuerySchema.js +153 -0
  25. package/dist/middleware/access.js +24 -0
  26. package/dist/middleware/ensureContentType.js +15 -0
  27. package/dist/middleware/filterAndFindById.js +24 -0
  28. package/dist/middleware/onError.js +21 -0
  29. package/dist/middleware/outputFn.js +18 -0
  30. package/dist/middleware/prepareOutput.js +81 -0
  31. package/dist/middleware/prepareQuery.js +17 -0
  32. package/dist/moredots.js +11 -0
  33. package/dist/operations.js +246 -0
  34. package/dist/resource_filter.js +105 -0
  35. package/dist/types.js +1 -0
  36. package/dist/weedout.js +19 -0
  37. package/package.json +62 -62
  38. package/CHANGELOG.md +0 -92
  39. package/index.d.ts +0 -45
  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 -123
  50. package/src/operations.js +0 -274
  51. package/src/resource_filter.js +0 -192
@@ -0,0 +1,153 @@
1
+ import { z } from "zod";
2
+ const PopulateOptionsSchema = z.object({
3
+ path: z.string(),
4
+ match: z.record(z.unknown()).optional(),
5
+ options: z.record(z.unknown()).optional(),
6
+ select: z.string().optional(),
7
+ // Configure populate query to not use strict populate to maintain
8
+ // behavior from Mongoose previous to v6 (unless already configured)
9
+ strictPopulate: z.boolean().optional().default(false)
10
+ });
11
+ const PopulateSchema = z.preprocess((value)=>{
12
+ if (typeof value === "string") {
13
+ if (value.startsWith("{")) {
14
+ return JSON.parse(`[${value}]`);
15
+ }
16
+ if (value.startsWith("[")) {
17
+ return JSON.parse(value);
18
+ }
19
+ return value;
20
+ }
21
+ return Array.isArray(value) ? value : [
22
+ value
23
+ ];
24
+ }, z.union([
25
+ z.string(),
26
+ z.array(PopulateOptionsSchema)
27
+ ]));
28
+ const SelectSchema = z.preprocess((value)=>{
29
+ const fieldToRecord = (field)=>{
30
+ if (field.startsWith("-")) {
31
+ return [
32
+ field.substring(1),
33
+ 0
34
+ ];
35
+ }
36
+ return [
37
+ field,
38
+ 1
39
+ ];
40
+ };
41
+ if (typeof value === "string") {
42
+ if (value.startsWith("{")) {
43
+ return JSON.parse(value);
44
+ }
45
+ return Object.fromEntries(value.split(",").filter(Boolean).map(fieldToRecord));
46
+ }
47
+ if (Array.isArray(value)) {
48
+ return Object.fromEntries(value.map(fieldToRecord));
49
+ }
50
+ return value;
51
+ }, z.record(z.number().min(0).max(1)));
52
+ const SortSchema = z.preprocess((value)=>{
53
+ if (typeof value === "string" && value.startsWith("{")) {
54
+ return JSON.parse(value);
55
+ }
56
+ return value;
57
+ }, z.union([
58
+ z.string(),
59
+ z.record(z.enum([
60
+ "asc",
61
+ "desc",
62
+ "ascending",
63
+ "descending",
64
+ "-1",
65
+ "1"
66
+ ])),
67
+ z.record(z.number().min(-1).max(1))
68
+ ]));
69
+ const LimitSkipSchema = z.preprocess((value)=>{
70
+ if (typeof value !== "string") {
71
+ return value;
72
+ }
73
+ return Number(value);
74
+ }, z.number());
75
+ export function getQueryOptionsSchema({ allowRegex }) {
76
+ const QuerySchema = z.preprocess((value)=>{
77
+ if (!allowRegex && `${value}`.toLowerCase().includes("$regex")) {
78
+ throw new Error("regex_not_allowed");
79
+ }
80
+ if (typeof value !== "string") {
81
+ return value;
82
+ }
83
+ return JSON.parse(value);
84
+ }, z.record(z.unknown())).transform((value)=>{
85
+ return Object.fromEntries(Object.entries(value).map(([key, value])=>{
86
+ if (Array.isArray(value) && !key.startsWith("$")) {
87
+ return [
88
+ key,
89
+ {
90
+ $in: value
91
+ }
92
+ ];
93
+ }
94
+ return [
95
+ key,
96
+ value
97
+ ];
98
+ }));
99
+ });
100
+ return z.object({
101
+ query: QuerySchema.optional(),
102
+ populate: PopulateSchema.optional(),
103
+ select: SelectSchema.optional(),
104
+ sort: SortSchema.optional(),
105
+ limit: LimitSkipSchema.optional(),
106
+ skip: LimitSkipSchema.optional(),
107
+ distinct: z.string().optional()
108
+ }).transform((value)=>{
109
+ if (typeof value.populate === "undefined") {
110
+ return value;
111
+ }
112
+ const populate = typeof value.populate === "string" ? value.populate.split(",").filter(Boolean).map((field)=>{
113
+ const pop = {
114
+ path: field,
115
+ strictPopulate: false
116
+ };
117
+ if (!value.select) {
118
+ return pop;
119
+ }
120
+ for (const [k, v] of Object.entries(value.select)){
121
+ if (k.startsWith(`${field}.`)) {
122
+ if (pop.select) {
123
+ pop.select += " ";
124
+ } else {
125
+ pop.select = "";
126
+ }
127
+ if (v === 0) {
128
+ pop.select += "-";
129
+ }
130
+ pop.select += k.substring(field.length + 1);
131
+ delete value.select[k];
132
+ }
133
+ }
134
+ // If other specific fields are selected, add the populated field
135
+ if (Object.keys(value.select).length > 0 && !value.select[field]) {
136
+ value.select[field] = 1;
137
+ }
138
+ return pop;
139
+ }) : value.populate;
140
+ return {
141
+ ...value,
142
+ populate
143
+ };
144
+ }).transform((value)=>{
145
+ if (!value.populate || Array.isArray(value.populate) && value.populate.length === 0) {
146
+ delete value.populate;
147
+ }
148
+ if (!value.select || Object.keys(value.select).length === 0) {
149
+ delete value.select;
150
+ }
151
+ return value;
152
+ });
153
+ }
@@ -0,0 +1,24 @@
1
+ import { getErrorHandler } from "../errorHandler.js";
2
+ export function getAccessHandler(options) {
3
+ const errorHandler = getErrorHandler(options);
4
+ const fn = function access(req, res, next) {
5
+ const handler = function(access) {
6
+ if (![
7
+ "public",
8
+ "private",
9
+ "protected"
10
+ ].includes(access)) {
11
+ throw new Error('Unsupported access, must be "public", "private" or "protected"');
12
+ }
13
+ req.access = access;
14
+ next();
15
+ };
16
+ const result = options.access(req);
17
+ if (typeof result === "string") {
18
+ handler(result);
19
+ } else {
20
+ result.then(handler).catch((err)=>errorHandler(err, req, res, next));
21
+ }
22
+ };
23
+ return fn;
24
+ }
@@ -0,0 +1,15 @@
1
+ import { getErrorHandler } from "../errorHandler.js";
2
+ export function getEnsureContentTypeHandler(options) {
3
+ const errorHandler = getErrorHandler(options);
4
+ const fn = function ensureContentType(req, res, next) {
5
+ const contentType = req.headers["content-type"];
6
+ if (!contentType) {
7
+ return errorHandler(new Error("missing_content_type"), req, res, next);
8
+ }
9
+ if (!contentType.includes("application/json")) {
10
+ return errorHandler(new Error("invalid_content_type"), req, res, next);
11
+ }
12
+ next();
13
+ };
14
+ return fn;
15
+ }
@@ -0,0 +1,24 @@
1
+ import { STATUS_CODES } from "http";
2
+ import { getErrorHandler } from "../errorHandler.js";
3
+ export function getFilterAndFindByIdHandler(options, model) {
4
+ const errorHandler = getErrorHandler(options);
5
+ const fn = function filterAndFindById(req, res, next) {
6
+ const contextModel = model;
7
+ if (!req.params.id) {
8
+ return next();
9
+ }
10
+ options.contextFilter(contextModel, req, (filteredContext)=>{
11
+ filteredContext// @ts-expect-error this is fine 🐢πŸ”₯
12
+ .findOne().and({
13
+ [options.idProperty]: req.params.id
14
+ }).lean(false).read(options.readPreference || "p").exec().then((doc)=>{
15
+ if (!doc) {
16
+ return errorHandler(new Error(STATUS_CODES[404]), req, res, next);
17
+ }
18
+ req.erm.document = doc;
19
+ next();
20
+ }).catch((err)=>errorHandler(err, req, res, next));
21
+ });
22
+ };
23
+ return fn;
24
+ }
@@ -0,0 +1,21 @@
1
+ import { serializeError } from "serialize-error";
2
+ export function getOnErrorHandler(isExpress) {
3
+ const fn = function onError(err, req, res) {
4
+ const serializedErr = serializeError(err);
5
+ delete serializedErr.stack;
6
+ if (serializedErr.errors) {
7
+ for(const key in serializedErr.errors){
8
+ delete serializedErr.errors[key].reason;
9
+ delete serializedErr.errors[key].stack;
10
+ }
11
+ }
12
+ res.setHeader("Content-Type", "application/json");
13
+ if (isExpress) {
14
+ res.status(req.erm.statusCode || 500).send(serializedErr);
15
+ } else {
16
+ // @ts-expect-error restify
17
+ res.send(req.erm.statusCode, serializedErr);
18
+ }
19
+ };
20
+ return fn;
21
+ }
@@ -0,0 +1,18 @@
1
+ export function getOutputFnHandler(isExpress) {
2
+ const fn = function outputFn(req, res) {
3
+ if (!req.erm.statusCode) {
4
+ throw new Error("statusCode not set");
5
+ }
6
+ if (isExpress) {
7
+ if (req.erm.result) {
8
+ res.status(req.erm.statusCode).json(req.erm.result);
9
+ } else {
10
+ res.sendStatus(req.erm.statusCode);
11
+ }
12
+ } else {
13
+ // @ts-expect-error restify
14
+ res.send(req.erm.statusCode, req.erm.result);
15
+ }
16
+ };
17
+ return fn;
18
+ }
@@ -0,0 +1,81 @@
1
+ import { getErrorHandler } from "../errorHandler.js";
2
+ function isDefined(arg) {
3
+ return typeof arg !== "undefined";
4
+ }
5
+ export function getPrepareOutputHandler(options, modelName, filter) {
6
+ const errorHandler = getErrorHandler(options);
7
+ const fn = function prepareOutput(req, res, next) {
8
+ const postMiddleware = (()=>{
9
+ switch(req.method.toLowerCase()){
10
+ case "get":
11
+ {
12
+ return Array.isArray(options.postRead) ? options.postRead : [
13
+ options.postRead
14
+ ];
15
+ }
16
+ case "post":
17
+ {
18
+ if (req.erm.statusCode === 201) {
19
+ return Array.isArray(options.postCreate) ? options.postCreate : [
20
+ options.postCreate
21
+ ];
22
+ }
23
+ return Array.isArray(options.postUpdate) ? options.postUpdate : [
24
+ options.postUpdate
25
+ ];
26
+ }
27
+ case "put":
28
+ case "patch":
29
+ {
30
+ return Array.isArray(options.postUpdate) ? options.postUpdate : [
31
+ options.postUpdate
32
+ ];
33
+ }
34
+ case "delete":
35
+ {
36
+ return Array.isArray(options.postDelete) ? options.postDelete : [
37
+ options.postDelete
38
+ ];
39
+ }
40
+ default:
41
+ {
42
+ return [];
43
+ }
44
+ }
45
+ })().filter(isDefined);
46
+ const callback = ()=>{
47
+ // TODO: this will, but should not, filter /count queries
48
+ if (req.erm.result) {
49
+ req.erm.result = filter.filterObject(req.erm.result, {
50
+ access: req.access,
51
+ modelName,
52
+ // @ts-expect-error this is fine 🐢πŸ”₯
53
+ populate: req.erm.query?.populate
54
+ });
55
+ }
56
+ if (options.totalCountHeader && typeof req.erm.totalCount === "number") {
57
+ res.header(typeof options.totalCountHeader === "string" ? options.totalCountHeader : "X-Total-Count", `${req.erm.totalCount}`);
58
+ }
59
+ const promise = options.outputFn(req, res);
60
+ if (options.postProcess) {
61
+ if (promise && typeof promise.then === "function") {
62
+ promise.then(()=>{
63
+ options.postProcess?.(req, res);
64
+ }).catch((err)=>errorHandler(err, req, res, next));
65
+ } else {
66
+ options.postProcess(req, res);
67
+ }
68
+ }
69
+ };
70
+ if (!postMiddleware || postMiddleware.length === 0) {
71
+ return callback();
72
+ }
73
+ postMiddleware.reduce(async (acc, middleware)=>{
74
+ await acc;
75
+ return new Promise((resolve, reject)=>{
76
+ middleware(req, res, (err)=>err ? reject(err) : resolve(err));
77
+ });
78
+ }, Promise.resolve()).then(callback).catch((err)=>errorHandler(err, req, res, next));
79
+ };
80
+ return fn;
81
+ }
@@ -0,0 +1,17 @@
1
+ import { getErrorHandler } from "../errorHandler.js";
2
+ import { getQueryOptionsSchema } from "../getQuerySchema.js";
3
+ export function getPrepareQueryHandler(options) {
4
+ const errorHandler = getErrorHandler(options);
5
+ const fn = function prepareQuery(req, res, next) {
6
+ req.erm = req.erm || {};
7
+ try {
8
+ req.erm.query = getQueryOptionsSchema({
9
+ allowRegex: options.allowRegex
10
+ }).parse(req.query || {});
11
+ next();
12
+ } catch (e) {
13
+ return errorHandler(new Error("invalid_json_query"), req, res, next);
14
+ }
15
+ };
16
+ return fn;
17
+ }
@@ -0,0 +1,11 @@
1
+ import isPlainObject from "lodash.isplainobject";
2
+ export function moredots(src, dst = {}, prefix = "") {
3
+ for (const [key, value] of Object.entries(src)){
4
+ if (isPlainObject(value)) {
5
+ moredots(value, dst, `${prefix}${key}.`);
6
+ } else {
7
+ dst[`${prefix}${key}`] = value;
8
+ }
9
+ }
10
+ return dst;
11
+ }
@@ -0,0 +1,246 @@
1
+ import { STATUS_CODES } from "http";
2
+ import isPlainObject from "lodash.isplainobject";
3
+ import { getBuildQuery } from "./buildQuery.js";
4
+ import { getErrorHandler } from "./errorHandler.js";
5
+ import { moredots } from "./moredots.js";
6
+ export function operations(model, options, filter) {
7
+ const buildQuery = getBuildQuery(options);
8
+ const errorHandler = getErrorHandler(options);
9
+ function findById(filteredContext, id) {
10
+ return filteredContext.findOne().and([
11
+ {
12
+ [options.idProperty]: id
13
+ }
14
+ ]);
15
+ }
16
+ function isDistinctExcluded(req) {
17
+ if (!req.erm.query?.distinct) {
18
+ return false;
19
+ }
20
+ return filter.getExcluded({
21
+ access: req.access,
22
+ modelName: model.modelName
23
+ }).includes(req.erm.query.distinct);
24
+ }
25
+ const getItems = function(req, res, next) {
26
+ const contextModel = model;
27
+ if (isDistinctExcluded(req)) {
28
+ req.erm.result = [];
29
+ req.erm.statusCode = 200;
30
+ return next();
31
+ }
32
+ options.contextFilter(contextModel, req, (filteredContext)=>{
33
+ buildQuery(// @ts-expect-error this is fine 🐢πŸ”₯
34
+ filteredContext.find(), req.erm.query).then((items)=>{
35
+ req.erm.result = items;
36
+ req.erm.statusCode = 200;
37
+ if (options.totalCountHeader && !req.erm.query?.distinct) {
38
+ options.contextFilter(contextModel, req, (countFilteredContext)=>{
39
+ buildQuery(countFilteredContext.countDocuments(), {
40
+ ...req.erm.query,
41
+ skip: 0,
42
+ limit: 0
43
+ }).then((count)=>{
44
+ req.erm.totalCount = count;
45
+ next();
46
+ }).catch((err)=>errorHandler(err, req, res, next));
47
+ });
48
+ } else {
49
+ next();
50
+ }
51
+ }).catch((err)=>errorHandler(err, req, res, next));
52
+ });
53
+ };
54
+ const getCount = function(req, res, next) {
55
+ const contextModel = model;
56
+ options.contextFilter(contextModel, req, (filteredContext)=>{
57
+ buildQuery(filteredContext.countDocuments(), req.erm.query).then((count)=>{
58
+ req.erm.result = {
59
+ count: count
60
+ };
61
+ req.erm.statusCode = 200;
62
+ next();
63
+ }).catch((err)=>errorHandler(err, req, res, next));
64
+ });
65
+ };
66
+ const getShallow = function(req, res, next) {
67
+ const contextModel = model;
68
+ options.contextFilter(contextModel, req, (filteredContext)=>{
69
+ buildQuery(// @ts-expect-error this is fine 🐢πŸ”₯
70
+ findById(filteredContext, req.params.id), req.erm.query).then((item)=>{
71
+ if (!item) {
72
+ return errorHandler(new Error(STATUS_CODES[404]), req, res, next);
73
+ }
74
+ for(const prop in item){
75
+ item[prop] = typeof item[prop] === "object" && prop !== "_id" ? true : item[prop];
76
+ }
77
+ req.erm.result = item;
78
+ req.erm.statusCode = 200;
79
+ next();
80
+ }).catch((err)=>errorHandler(err, req, res, next));
81
+ });
82
+ };
83
+ const deleteItems = function(req, res, next) {
84
+ const contextModel = model;
85
+ options.contextFilter(contextModel, req, (filteredContext)=>{
86
+ buildQuery(filteredContext.deleteMany(), req.erm.query).then(()=>{
87
+ req.erm.statusCode = 204;
88
+ next();
89
+ }).catch((err)=>errorHandler(err, req, res, next));
90
+ });
91
+ };
92
+ const getItem = function(req, res, next) {
93
+ const contextModel = model;
94
+ if (isDistinctExcluded(req)) {
95
+ req.erm.result = [];
96
+ req.erm.statusCode = 200;
97
+ return next();
98
+ }
99
+ options.contextFilter(contextModel, req, (filteredContext)=>{
100
+ buildQuery(// @ts-expect-error this is fine 🐢πŸ”₯
101
+ findById(filteredContext, req.params.id), req.erm.query).then((item)=>{
102
+ if (!item) {
103
+ return errorHandler(new Error(STATUS_CODES[404]), req, res, next);
104
+ }
105
+ req.erm.result = item;
106
+ req.erm.statusCode = 200;
107
+ next();
108
+ }).catch((err)=>errorHandler(err, req, res, next));
109
+ });
110
+ };
111
+ const deleteItem = function(req, res, next) {
112
+ const contextModel = model;
113
+ if (options.findOneAndRemove) {
114
+ options.contextFilter(contextModel, req, (filteredContext)=>{
115
+ // @ts-expect-error this is fine 🐢πŸ”₯
116
+ findById(filteredContext, req.params.id).findOneAndRemove().then((item)=>{
117
+ if (!item) {
118
+ return errorHandler(new Error(STATUS_CODES[404]), req, res, next);
119
+ }
120
+ req.erm.statusCode = 204;
121
+ next();
122
+ }).catch((err)=>errorHandler(err, req, res, next));
123
+ });
124
+ } else {
125
+ req.erm.document?.remove().then(()=>{
126
+ req.erm.statusCode = 204;
127
+ next();
128
+ }).catch((err)=>errorHandler(err, req, res, next));
129
+ }
130
+ };
131
+ const createObject = function(req, res, next) {
132
+ const contextModel = model;
133
+ req.body = filter.filterObject(req.body || {}, {
134
+ access: req.access,
135
+ modelName: model.modelName,
136
+ // @ts-expect-error this is fine 🐢πŸ”₯
137
+ populate: req.erm.query?.populate
138
+ });
139
+ if (req.body._id === null) {
140
+ delete req.body._id;
141
+ }
142
+ // @ts-expect-error this is fine 🐢πŸ”₯
143
+ if (contextModel.schema.options.versionKey) {
144
+ // @ts-expect-error this is fine 🐢πŸ”₯
145
+ delete req.body[contextModel.schema.options.versionKey];
146
+ }
147
+ contextModel.create(req.body).then((item)=>{
148
+ // @ts-expect-error this is fine 🐢πŸ”₯
149
+ return contextModel.populate(item, req.erm.query?.populate || []);
150
+ }).then((item)=>{
151
+ req.erm.result = item;
152
+ req.erm.statusCode = 201;
153
+ next();
154
+ }).catch((err)=>errorHandler(err, req, res, next));
155
+ };
156
+ const modifyObject = function(req, res, next) {
157
+ const contextModel = model;
158
+ req.body = filter.filterObject(req.body || {}, {
159
+ access: req.access,
160
+ modelName: model.modelName,
161
+ // @ts-expect-error this is fine 🐢πŸ”₯
162
+ populate: req.erm.query?.populate
163
+ });
164
+ delete req.body._id;
165
+ // @ts-expect-error this is fine 🐢πŸ”₯
166
+ if (contextModel.schema.options.versionKey) {
167
+ // @ts-expect-error this is fine 🐢πŸ”₯
168
+ delete req.body[contextModel.schema.options.versionKey];
169
+ }
170
+ function depopulate(src) {
171
+ const dst = {};
172
+ for (const [key, value] of Object.entries(src)){
173
+ const path = contextModel.schema.path(key);
174
+ // @ts-expect-error this is fine 🐢πŸ”₯
175
+ if (path && path.caster && path.caster.instance === "ObjectID") {
176
+ if (Array.isArray(value)) {
177
+ for(let j = 0; j < value.length; ++j){
178
+ if (typeof value[j] === "object") {
179
+ dst[key] = dst[key] || [];
180
+ // @ts-expect-error this is fine 🐢πŸ”₯
181
+ dst[key].push(value[j]._id);
182
+ }
183
+ }
184
+ } else if (isPlainObject(value)) {
185
+ dst[key] = value._id;
186
+ }
187
+ } else if (isPlainObject(value)) {
188
+ if (path && path.instance === "ObjectID") {
189
+ dst[key] = value._id;
190
+ } else {
191
+ dst[key] = depopulate(value);
192
+ }
193
+ }
194
+ if (typeof dst[key] === "undefined") {
195
+ dst[key] = value;
196
+ }
197
+ }
198
+ return dst;
199
+ }
200
+ const cleanBody = moredots(depopulate(req.body));
201
+ if (options.findOneAndUpdate) {
202
+ options.contextFilter(contextModel, req, (filteredContext)=>{
203
+ // @ts-expect-error this is fine 🐢πŸ”₯
204
+ findById(filteredContext, req.params.id).findOneAndUpdate({}, {
205
+ $set: cleanBody
206
+ }, {
207
+ new: true,
208
+ upsert: options.upsert,
209
+ runValidators: options.runValidators
210
+ }).exec().then((item)=>{
211
+ // @ts-expect-error this is fine 🐢πŸ”₯
212
+ return contextModel.populate(item, req.erm.query?.populate || []);
213
+ }).then((item)=>{
214
+ if (!item) {
215
+ return errorHandler(new Error(STATUS_CODES[404]), req, res, next);
216
+ }
217
+ req.erm.result = item;
218
+ req.erm.statusCode = 200;
219
+ next();
220
+ }).catch((err)=>errorHandler(err, req, res, next));
221
+ });
222
+ } else {
223
+ for (const [key, value] of Object.entries(cleanBody)){
224
+ req.erm.document?.set(key, value);
225
+ }
226
+ req.erm.document?.save().then((item)=>{
227
+ // @ts-expect-error this is fine 🐢πŸ”₯
228
+ return contextModel.populate(item, req.erm.query?.populate || []);
229
+ }).then((item)=>{
230
+ req.erm.result = item;
231
+ req.erm.statusCode = 200;
232
+ next();
233
+ }).catch((err)=>errorHandler(err, req, res, next));
234
+ }
235
+ };
236
+ return {
237
+ getItems,
238
+ getCount,
239
+ getItem,
240
+ getShallow,
241
+ createObject,
242
+ modifyObject,
243
+ deleteItems,
244
+ deleteItem
245
+ };
246
+ }