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.
package/README.md CHANGED
@@ -3,8 +3,6 @@
3
3
  Easily create a flexible REST interface for mongoose models.
4
4
 
5
5
  [![Build Status](https://github.com/florianholzapfel/express-restify-mongoose/actions/workflows/node.js.yml/badge.svg)](https://github.com/florianholzapfel/express-restify-mongoose/actions/workflows/node.js.yml)
6
- [](https://sonarcloud.io/project/overview?id=florianholzapfel_express-restify-mongoose)
7
- [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=florianholzapfel_express-restify-mongoose&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=florianholzapfel_express-restify-mongoose)
8
6
  [![npm version](https://badge.fury.io/js/express-restify-mongoose.svg)](https://badge.fury.io/js/express-restify-mongoose)
9
7
 
10
8
  ## Getting started
@@ -19,12 +17,14 @@ npm install express-restify-mongoose --save
19
17
 
20
18
  ## Compatibility
21
19
 
22
- | This library | Mongoose |
23
- | ------------ | -------- |
24
- | >= 7.0.0 | >= 6.x |
25
- | >= 6.0.0 | >= 5.8.0 |
26
- | >= 1.0.0 | 4.x |
27
- | 0.7.5 | 3.x |
20
+ | This library | Mongoose | MongoDB | NodeJS
21
+ | ------------ | ----------- | ----------- | --------
22
+ | >= 9.0.0 | 6.x - 8.x | 3.6.x - 7.x | >=16
23
+ | >= 8.0.0 | 6.x | 3.6.x - 6.x | >=18
24
+ | >= 7.0.0 | 6.x | 3.6.x - 6.x | >=14
25
+ | >= 6.0.0 | 5.8.0 - 6.x | 3.6.x - 6.x | >=6
26
+ | >= 1.0.0 | 4.x | 2.4 - 3.4 | >=0.10
27
+ | 0.7.5 | 3.x | 2.4 - 3.0 | *
28
28
 
29
29
  ## Contributing
30
30
 
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getBuildQuery", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getBuildQuery;
9
+ }
10
+ });
11
+ function getBuildQuery(options) {
12
+ return function buildQuery(query, queryOptions) {
13
+ const promise = new Promise((resolve)=>{
14
+ if (!queryOptions) {
15
+ return resolve(query);
16
+ }
17
+ if (queryOptions.query) {
18
+ query.where(queryOptions.query);
19
+ }
20
+ if (queryOptions.skip) {
21
+ query.skip(queryOptions.skip);
22
+ }
23
+ if (options.limit && (!queryOptions.limit || queryOptions.limit > options.limit)) {
24
+ queryOptions.limit = options.limit;
25
+ }
26
+ if (queryOptions.limit && // @ts-expect-error this is fine 🐢πŸ”₯
27
+ query.op !== "countDocuments" && !queryOptions.distinct) {
28
+ query.limit(queryOptions.limit);
29
+ }
30
+ if (queryOptions.sort) {
31
+ // Necessary to support Mongoose 8
32
+ if (typeof queryOptions.sort === 'object') {
33
+ Object.keys(queryOptions.sort).forEach((key)=>{
34
+ // @ts-expect-error this is fine 🐢πŸ”₯
35
+ queryOptions.sort[key] = Number(queryOptions.sort[key]);
36
+ });
37
+ }
38
+ // @ts-expect-error this is fine 🐢πŸ”₯
39
+ query.sort(queryOptions.sort);
40
+ }
41
+ if (queryOptions.populate) {
42
+ // @ts-expect-error this is fine 🐢πŸ”₯
43
+ query.populate(queryOptions.populate);
44
+ }
45
+ if (queryOptions.select) {
46
+ query.select(queryOptions.select);
47
+ }
48
+ if (queryOptions.distinct) {
49
+ query.distinct(queryOptions.distinct);
50
+ }
51
+ if (options.readPreference) {
52
+ query.read(options.readPreference);
53
+ }
54
+ if (options.lean) {
55
+ query.lean(options.lean);
56
+ }
57
+ resolve(query);
58
+ });
59
+ return promise;
60
+ };
61
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "detective", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return detective;
9
+ }
10
+ });
11
+ function detective(model, path) {
12
+ const keys = path.split(".");
13
+ let schema = model.schema;
14
+ let schemaPath = "";
15
+ for(let i = 0, length = keys.length; i < length; i++){
16
+ if (schemaPath.length > 0) {
17
+ schemaPath += ".";
18
+ }
19
+ schemaPath += keys[i];
20
+ if (schema.path(schemaPath) && schema.path(schemaPath).schema) {
21
+ schema = schema.path(schemaPath).schema;
22
+ }
23
+ }
24
+ if (!schema) {
25
+ return;
26
+ }
27
+ // @ts-expect-error this is fine 🐢πŸ”₯
28
+ schemaPath = schema.path(keys[keys.length - 1]) || schema.path(schemaPath);
29
+ if (!schemaPath && (!model || !model.discriminators)) {
30
+ return;
31
+ }
32
+ // @ts-expect-error this is fine 🐢πŸ”₯
33
+ if (schemaPath.caster && schemaPath.caster.options) {
34
+ // @ts-expect-error this is fine 🐢πŸ”₯
35
+ return schemaPath.caster.options.ref;
36
+ // @ts-expect-error this is fine 🐢πŸ”₯
37
+ } else if (schemaPath.options) {
38
+ // @ts-expect-error this is fine 🐢πŸ”₯
39
+ return schemaPath.options.ref;
40
+ }
41
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getErrorHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getErrorHandler;
9
+ }
10
+ });
11
+ const _http = require("http");
12
+ function getErrorHandler(options) {
13
+ const fn = function errorHandler(err, req, res, next) {
14
+ if (err.message === _http.STATUS_CODES[404] || req.params?.id && err.path === options.idProperty && err.name === "CastError") {
15
+ req.erm.statusCode = 404;
16
+ } else {
17
+ req.erm.statusCode = req.erm.statusCode && req.erm.statusCode >= 400 ? req.erm.statusCode : 400;
18
+ }
19
+ options.onError(err, req, res, next);
20
+ };
21
+ return fn;
22
+ }
@@ -0,0 +1,45 @@
1
+ import { RequestHandler, Request, Response, ErrorRequestHandler, Application } from 'express';
2
+ import mongoose from 'mongoose';
3
+
4
+ type Access = "private" | "protected" | "public";
5
+ type OutputFn = (req: Request, res: Response) => void | Promise<void>;
6
+ type ReadPreference = "p" | "primary" | "pp" | "primaryPreferred" | "s" | "secondary" | "sp" | "secondaryPreferred" | "n" | "nearest";
7
+ type Options = {
8
+ prefix: `/${string}`;
9
+ version: `/v${number}`;
10
+ idProperty: string;
11
+ restify: boolean;
12
+ name?: string;
13
+ allowRegex: boolean;
14
+ runValidators: boolean;
15
+ readPreference: ReadPreference;
16
+ totalCountHeader: boolean | string;
17
+ private: string[];
18
+ protected: string[];
19
+ lean: boolean;
20
+ limit?: number;
21
+ findOneAndRemove: boolean;
22
+ findOneAndUpdate: boolean;
23
+ upsert: boolean;
24
+ preMiddleware: RequestHandler | RequestHandler[];
25
+ preCreate: RequestHandler | RequestHandler[];
26
+ preRead: RequestHandler | RequestHandler[];
27
+ preUpdate: RequestHandler | RequestHandler[];
28
+ preDelete: RequestHandler | RequestHandler[];
29
+ access?: (req: Request) => Access | Promise<Access>;
30
+ contextFilter: (model: mongoose.Model<unknown>, req: Request, done: (query: mongoose.Model<unknown> | mongoose.Query<unknown, unknown>) => void) => void;
31
+ postCreate?: RequestHandler | RequestHandler[];
32
+ postRead?: RequestHandler | RequestHandler[];
33
+ postUpdate?: RequestHandler | RequestHandler[];
34
+ postDelete?: RequestHandler | RequestHandler[];
35
+ outputFn: OutputFn;
36
+ postProcess?: (req: Request, res: Response) => void;
37
+ onError: ErrorRequestHandler;
38
+ modelFactory?: {
39
+ getModel: (req: Request) => mongoose.Model<unknown>;
40
+ };
41
+ };
42
+
43
+ declare function serve(app: Application, model: mongoose.Model<unknown>, options?: Partial<Options>): string;
44
+
45
+ export { serve };
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "serve", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return serve;
9
+ }
10
+ });
11
+ const _util = require("util");
12
+ const _access = require("./middleware/access.js");
13
+ const _ensureContentType = require("./middleware/ensureContentType.js");
14
+ const _filterAndFindById = require("./middleware/filterAndFindById.js");
15
+ const _onError = require("./middleware/onError.js");
16
+ const _outputFn = require("./middleware/outputFn.js");
17
+ const _prepareOutput = require("./middleware/prepareOutput.js");
18
+ const _prepareQuery = require("./middleware/prepareQuery.js");
19
+ const _operations = require("./operations.js");
20
+ const _resource_filter = require("./resource_filter.js");
21
+ const defaultOptions = {
22
+ prefix: "/api",
23
+ version: "/v1",
24
+ idProperty: "_id",
25
+ restify: false,
26
+ allowRegex: false,
27
+ runValidators: false,
28
+ readPreference: "primary",
29
+ totalCountHeader: false,
30
+ private: [],
31
+ protected: [],
32
+ lean: true,
33
+ findOneAndUpdate: true,
34
+ findOneAndRemove: true,
35
+ upsert: false,
36
+ preMiddleware: [],
37
+ preCreate: [],
38
+ preRead: [],
39
+ preUpdate: [],
40
+ preDelete: []
41
+ };
42
+ const filter = new _resource_filter.Filter();
43
+ function serve(app, model, options = {}) {
44
+ const serveOptions = {
45
+ ...defaultOptions,
46
+ name: typeof options.name === "string" ? options.name : model.modelName,
47
+ contextFilter: (model, req, done)=>done(model),
48
+ outputFn: (0, _outputFn.getOutputFnHandler)(typeof options.restify === "boolean" ? !options.restify : !defaultOptions.restify),
49
+ onError: (0, _onError.getOnErrorHandler)(typeof options.restify === "boolean" ? !options.restify : !defaultOptions.restify),
50
+ ...options
51
+ };
52
+ model.schema.eachPath((name, path)=>{
53
+ if (path.options.access) {
54
+ switch(path.options.access.toLowerCase()){
55
+ case "private":
56
+ serveOptions.private.push(name);
57
+ break;
58
+ case "protected":
59
+ serveOptions.protected.push(name);
60
+ break;
61
+ }
62
+ }
63
+ });
64
+ filter.add(model, {
65
+ filteredKeys: {
66
+ private: serveOptions.private,
67
+ protected: serveOptions.protected
68
+ }
69
+ });
70
+ const ops = (0, _operations.operations)(model, serveOptions, filter);
71
+ let uriItem = `${serveOptions.prefix}${serveOptions.version}/${serveOptions.name}`;
72
+ if (uriItem.indexOf("/:id") === -1) {
73
+ uriItem += "/:id";
74
+ }
75
+ const uriItems = uriItem.replace("/:id", "");
76
+ const uriCount = uriItems + "/count";
77
+ const uriShallow = uriItem + "/shallow";
78
+ if (typeof app.delete === "undefined") {
79
+ // @ts-expect-error restify
80
+ app.delete = app.del;
81
+ }
82
+ app.use((req, res, next)=>{
83
+ req.erm = {};
84
+ next();
85
+ });
86
+ const accessMiddleware = serveOptions.access ? (0, _access.getAccessHandler)({
87
+ access: serveOptions.access,
88
+ idProperty: serveOptions.idProperty,
89
+ onError: serveOptions.onError
90
+ }) : [];
91
+ const ensureContentType = (0, _ensureContentType.getEnsureContentTypeHandler)(serveOptions);
92
+ const filterAndFindById = (0, _filterAndFindById.getFilterAndFindByIdHandler)(serveOptions, model);
93
+ const prepareQuery = (0, _prepareQuery.getPrepareQueryHandler)(serveOptions);
94
+ const prepareOutput = (0, _prepareOutput.getPrepareOutputHandler)(serveOptions, model.modelName, filter);
95
+ app.get(uriItems, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getItems, prepareOutput);
96
+ app.get(uriCount, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getCount, prepareOutput);
97
+ app.get(uriItem, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getItem, prepareOutput);
98
+ app.get(uriShallow, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getShallow, prepareOutput);
99
+ app.post(uriItems, prepareQuery, ensureContentType, serveOptions.preMiddleware, serveOptions.preCreate, accessMiddleware, ops.createObject, prepareOutput);
100
+ app.post(uriItem, (0, _util.deprecate)(prepareQuery, "express-restify-mongoose: in a future major version, the POST method to update resources will be removed. Use PATCH instead."), ensureContentType, serveOptions.preMiddleware, serveOptions.findOneAndUpdate ? [] : filterAndFindById, serveOptions.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput);
101
+ app.put(uriItem, (0, _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, serveOptions.preMiddleware, serveOptions.findOneAndUpdate ? [] : filterAndFindById, serveOptions.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput);
102
+ app.patch(uriItem, prepareQuery, ensureContentType, serveOptions.preMiddleware, serveOptions.findOneAndUpdate ? [] : filterAndFindById, serveOptions.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput);
103
+ app.delete(uriItems, prepareQuery, serveOptions.preMiddleware, serveOptions.preDelete, ops.deleteItems, prepareOutput);
104
+ app.delete(uriItem, prepareQuery, serveOptions.preMiddleware, serveOptions.findOneAndRemove ? [] : filterAndFindById, serveOptions.preDelete, ops.deleteItem, prepareOutput);
105
+ return uriItems;
106
+ }
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getQueryOptionsSchema", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getQueryOptionsSchema;
9
+ }
10
+ });
11
+ const _zod = require("zod");
12
+ const PopulateOptionsSchema = _zod.z.object({
13
+ path: _zod.z.string(),
14
+ match: _zod.z.record(_zod.z.unknown()).optional(),
15
+ options: _zod.z.record(_zod.z.unknown()).optional(),
16
+ select: _zod.z.string().optional(),
17
+ // Configure populate query to not use strict populate to maintain
18
+ // behavior from Mongoose previous to v6 (unless already configured)
19
+ strictPopulate: _zod.z.boolean().optional().default(false)
20
+ });
21
+ const PopulateSchema = _zod.z.preprocess((value)=>{
22
+ if (typeof value === "string") {
23
+ if (value.startsWith("{")) {
24
+ return JSON.parse(`[${value}]`);
25
+ }
26
+ if (value.startsWith("[")) {
27
+ return JSON.parse(value);
28
+ }
29
+ return value;
30
+ }
31
+ return Array.isArray(value) ? value : [
32
+ value
33
+ ];
34
+ }, _zod.z.union([
35
+ _zod.z.string(),
36
+ _zod.z.array(PopulateOptionsSchema)
37
+ ]));
38
+ const SelectSchema = _zod.z.preprocess((value)=>{
39
+ const fieldToRecord = (field)=>{
40
+ if (field.startsWith("-")) {
41
+ return [
42
+ field.substring(1),
43
+ 0
44
+ ];
45
+ }
46
+ return [
47
+ field,
48
+ 1
49
+ ];
50
+ };
51
+ if (typeof value === "string") {
52
+ if (value.startsWith("{")) {
53
+ return JSON.parse(value);
54
+ }
55
+ return Object.fromEntries(value.split(",").filter(Boolean).map(fieldToRecord));
56
+ }
57
+ if (Array.isArray(value)) {
58
+ return Object.fromEntries(value.map(fieldToRecord));
59
+ }
60
+ return value;
61
+ }, _zod.z.record(_zod.z.number().min(0).max(1)));
62
+ const SortSchema = _zod.z.preprocess((value)=>{
63
+ if (typeof value === "string" && value.startsWith("{")) {
64
+ return JSON.parse(value);
65
+ }
66
+ return value;
67
+ }, _zod.z.union([
68
+ _zod.z.string(),
69
+ _zod.z.record(_zod.z.enum([
70
+ "asc",
71
+ "desc",
72
+ "ascending",
73
+ "descending",
74
+ "-1",
75
+ "1"
76
+ ])),
77
+ _zod.z.record(_zod.z.number().min(-1).max(1))
78
+ ]));
79
+ const LimitSkipSchema = _zod.z.preprocess((value)=>{
80
+ if (typeof value !== "string") {
81
+ return value;
82
+ }
83
+ return Number(value);
84
+ }, _zod.z.number());
85
+ function getQueryOptionsSchema({ allowRegex }) {
86
+ const QuerySchema = _zod.z.preprocess((value)=>{
87
+ if (!allowRegex && `${value}`.toLowerCase().includes("$regex")) {
88
+ throw new Error("regex_not_allowed");
89
+ }
90
+ if (typeof value !== "string") {
91
+ return value;
92
+ }
93
+ return JSON.parse(value);
94
+ }, _zod.z.record(_zod.z.unknown())).transform((value)=>{
95
+ return Object.fromEntries(Object.entries(value).map(([key, value])=>{
96
+ if (Array.isArray(value) && !key.startsWith("$")) {
97
+ return [
98
+ key,
99
+ {
100
+ $in: value
101
+ }
102
+ ];
103
+ }
104
+ return [
105
+ key,
106
+ value
107
+ ];
108
+ }));
109
+ });
110
+ return _zod.z.object({
111
+ query: QuerySchema.optional(),
112
+ populate: PopulateSchema.optional(),
113
+ select: SelectSchema.optional(),
114
+ sort: SortSchema.optional(),
115
+ limit: LimitSkipSchema.optional(),
116
+ skip: LimitSkipSchema.optional(),
117
+ distinct: _zod.z.string().optional()
118
+ }).transform((value)=>{
119
+ if (typeof value.populate === "undefined") {
120
+ return value;
121
+ }
122
+ const populate = typeof value.populate === "string" ? value.populate.split(",").filter(Boolean).map((field)=>{
123
+ const pop = {
124
+ path: field,
125
+ strictPopulate: false
126
+ };
127
+ if (!value.select) {
128
+ return pop;
129
+ }
130
+ for (const [k, v] of Object.entries(value.select)){
131
+ if (k.startsWith(`${field}.`)) {
132
+ if (pop.select) {
133
+ pop.select += " ";
134
+ } else {
135
+ pop.select = "";
136
+ }
137
+ if (v === 0) {
138
+ pop.select += "-";
139
+ }
140
+ pop.select += k.substring(field.length + 1);
141
+ delete value.select[k];
142
+ }
143
+ }
144
+ // If other specific fields are selected, add the populated field
145
+ if (Object.keys(value.select).length > 0 && !value.select[field]) {
146
+ value.select[field] = 1;
147
+ }
148
+ return pop;
149
+ }) : value.populate;
150
+ return {
151
+ ...value,
152
+ populate
153
+ };
154
+ }).transform((value)=>{
155
+ if (!value.populate || Array.isArray(value.populate) && value.populate.length === 0) {
156
+ delete value.populate;
157
+ }
158
+ if (!value.select || Object.keys(value.select).length === 0) {
159
+ delete value.select;
160
+ }
161
+ return value;
162
+ });
163
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getAccessHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getAccessHandler;
9
+ }
10
+ });
11
+ const _errorHandler = require("../errorHandler.js");
12
+ function getAccessHandler(options) {
13
+ const errorHandler = (0, _errorHandler.getErrorHandler)(options);
14
+ const fn = function access(req, res, next) {
15
+ const handler = function(access) {
16
+ if (![
17
+ "public",
18
+ "private",
19
+ "protected"
20
+ ].includes(access)) {
21
+ throw new Error('Unsupported access, must be "public", "private" or "protected"');
22
+ }
23
+ req.access = access;
24
+ next();
25
+ };
26
+ const result = options.access(req);
27
+ if (typeof result === "string") {
28
+ handler(result);
29
+ } else {
30
+ result.then(handler).catch((err)=>errorHandler(err, req, res, next));
31
+ }
32
+ };
33
+ return fn;
34
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getEnsureContentTypeHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getEnsureContentTypeHandler;
9
+ }
10
+ });
11
+ const _errorHandler = require("../errorHandler.js");
12
+ function getEnsureContentTypeHandler(options) {
13
+ const errorHandler = (0, _errorHandler.getErrorHandler)(options);
14
+ const fn = function ensureContentType(req, res, next) {
15
+ const contentType = req.headers["content-type"];
16
+ if (!contentType) {
17
+ return errorHandler(new Error("missing_content_type"), req, res, next);
18
+ }
19
+ if (!contentType.includes("application/json")) {
20
+ return errorHandler(new Error("invalid_content_type"), req, res, next);
21
+ }
22
+ next();
23
+ };
24
+ return fn;
25
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getFilterAndFindByIdHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getFilterAndFindByIdHandler;
9
+ }
10
+ });
11
+ const _http = require("http");
12
+ const _errorHandler = require("../errorHandler.js");
13
+ function getFilterAndFindByIdHandler(options, model) {
14
+ const errorHandler = (0, _errorHandler.getErrorHandler)(options);
15
+ const fn = function filterAndFindById(req, res, next) {
16
+ const contextModel = model;
17
+ if (!req.params.id) {
18
+ return next();
19
+ }
20
+ options.contextFilter(contextModel, req, (filteredContext)=>{
21
+ filteredContext// @ts-expect-error this is fine 🐢πŸ”₯
22
+ .findOne().and({
23
+ [options.idProperty]: req.params.id
24
+ }).lean(false).read(options.readPreference || "p").exec().then((doc)=>{
25
+ if (!doc) {
26
+ return errorHandler(new Error(_http.STATUS_CODES[404]), req, res, next);
27
+ }
28
+ req.erm.document = doc;
29
+ next();
30
+ }).catch((err)=>errorHandler(err, req, res, next));
31
+ });
32
+ };
33
+ return fn;
34
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getOnErrorHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getOnErrorHandler;
9
+ }
10
+ });
11
+ const _serializeerror = require("serialize-error");
12
+ function getOnErrorHandler(isExpress) {
13
+ const fn = function onError(err, req, res) {
14
+ const serializedErr = (0, _serializeerror.serializeError)(err);
15
+ delete serializedErr.stack;
16
+ if (serializedErr.errors) {
17
+ for(const key in serializedErr.errors){
18
+ delete serializedErr.errors[key].reason;
19
+ delete serializedErr.errors[key].stack;
20
+ }
21
+ }
22
+ res.setHeader("Content-Type", "application/json");
23
+ if (isExpress) {
24
+ res.status(req.erm.statusCode || 500).send(serializedErr);
25
+ } else {
26
+ // @ts-expect-error restify
27
+ res.send(req.erm.statusCode, serializedErr);
28
+ }
29
+ };
30
+ return fn;
31
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getOutputFnHandler", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getOutputFnHandler;
9
+ }
10
+ });
11
+ function getOutputFnHandler(isExpress) {
12
+ const fn = function outputFn(req, res) {
13
+ if (!req.erm.statusCode) {
14
+ throw new Error("statusCode not set");
15
+ }
16
+ if (isExpress) {
17
+ if (req.erm.result) {
18
+ res.status(req.erm.statusCode).json(req.erm.result);
19
+ } else {
20
+ res.sendStatus(req.erm.statusCode);
21
+ }
22
+ } else {
23
+ // @ts-expect-error restify
24
+ res.send(req.erm.statusCode, req.erm.result);
25
+ }
26
+ };
27
+ return fn;
28
+ }