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.
- package/LICENSE +19 -19
- package/README.md +57 -52
- package/dist/buildQuery.js +44 -0
- package/dist/cjs/buildQuery.js +52 -0
- package/dist/cjs/detective.js +39 -0
- package/dist/cjs/errorHandler.js +20 -0
- package/dist/cjs/express-restify-mongoose.js +104 -0
- package/dist/cjs/getQuerySchema.js +161 -0
- package/dist/cjs/middleware/access.js +32 -0
- package/dist/cjs/middleware/ensureContentType.js +23 -0
- package/dist/cjs/middleware/filterAndFindById.js +32 -0
- package/dist/cjs/middleware/onError.js +29 -0
- package/dist/cjs/middleware/outputFn.js +26 -0
- package/dist/cjs/middleware/prepareOutput.js +89 -0
- package/dist/cjs/middleware/prepareQuery.js +25 -0
- package/dist/cjs/moredots.js +24 -0
- package/dist/cjs/operations.js +259 -0
- package/dist/cjs/resource_filter.js +113 -0
- package/dist/cjs/types.js +4 -0
- package/dist/cjs/weedout.js +27 -0
- package/dist/detective.js +31 -0
- package/dist/errorHandler.js +12 -0
- package/dist/express-restify-mongoose.d.ts +45 -0
- package/dist/express-restify-mongoose.js +96 -0
- package/dist/getQuerySchema.js +153 -0
- package/dist/middleware/access.js +24 -0
- package/dist/middleware/ensureContentType.js +15 -0
- package/dist/middleware/filterAndFindById.js +24 -0
- package/dist/middleware/onError.js +21 -0
- package/dist/middleware/outputFn.js +18 -0
- package/dist/middleware/prepareOutput.js +81 -0
- package/dist/middleware/prepareQuery.js +17 -0
- package/dist/moredots.js +11 -0
- package/dist/operations.js +246 -0
- package/dist/resource_filter.js +105 -0
- package/dist/types.js +1 -0
- package/dist/weedout.js +19 -0
- package/package.json +80 -85
- package/CHANGELOG.md +0 -92
- package/src/buildQuery.js +0 -55
- package/src/errorHandler.js +0 -17
- package/src/express-restify-mongoose.js +0 -144
- package/src/middleware/access.js +0 -26
- package/src/middleware/ensureContentType.js +0 -19
- package/src/middleware/filterAndFindById.js +0 -35
- package/src/middleware/onError.js +0 -26
- package/src/middleware/outputFn.js +0 -15
- package/src/middleware/prepareOutput.js +0 -75
- package/src/middleware/prepareQuery.js +0 -115
- package/src/operations.js +0 -274
- package/src/resource_filter.js +0 -192
|
@@ -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,96 @@
|
|
|
1
|
+
import { deprecate } from "util";
|
|
2
|
+
import { getAccessHandler } from "./middleware/access.js";
|
|
3
|
+
import { getEnsureContentTypeHandler } from "./middleware/ensureContentType.js";
|
|
4
|
+
import { getFilterAndFindByIdHandler } from "./middleware/filterAndFindById.js";
|
|
5
|
+
import { getOnErrorHandler } from "./middleware/onError.js";
|
|
6
|
+
import { getOutputFnHandler } from "./middleware/outputFn.js";
|
|
7
|
+
import { getPrepareOutputHandler } from "./middleware/prepareOutput.js";
|
|
8
|
+
import { getPrepareQueryHandler } from "./middleware/prepareQuery.js";
|
|
9
|
+
import { operations } from "./operations.js";
|
|
10
|
+
import { Filter } from "./resource_filter.js";
|
|
11
|
+
const defaultOptions = {
|
|
12
|
+
prefix: "/api",
|
|
13
|
+
version: "/v1",
|
|
14
|
+
idProperty: "_id",
|
|
15
|
+
restify: false,
|
|
16
|
+
allowRegex: false,
|
|
17
|
+
runValidators: false,
|
|
18
|
+
readPreference: "primary",
|
|
19
|
+
totalCountHeader: false,
|
|
20
|
+
private: [],
|
|
21
|
+
protected: [],
|
|
22
|
+
lean: true,
|
|
23
|
+
findOneAndUpdate: true,
|
|
24
|
+
findOneAndRemove: true,
|
|
25
|
+
upsert: false,
|
|
26
|
+
preMiddleware: [],
|
|
27
|
+
preCreate: [],
|
|
28
|
+
preRead: [],
|
|
29
|
+
preUpdate: [],
|
|
30
|
+
preDelete: []
|
|
31
|
+
};
|
|
32
|
+
const filter = new Filter();
|
|
33
|
+
export function serve(app, model, options = {}) {
|
|
34
|
+
const serveOptions = {
|
|
35
|
+
...defaultOptions,
|
|
36
|
+
name: typeof options.name === "string" ? options.name : model.modelName,
|
|
37
|
+
contextFilter: (model, req, done)=>done(model),
|
|
38
|
+
outputFn: getOutputFnHandler(typeof options.restify === "boolean" ? !options.restify : !defaultOptions.restify),
|
|
39
|
+
onError: getOnErrorHandler(typeof options.restify === "boolean" ? !options.restify : !defaultOptions.restify),
|
|
40
|
+
...options
|
|
41
|
+
};
|
|
42
|
+
model.schema.eachPath((name, path)=>{
|
|
43
|
+
if (path.options.access) {
|
|
44
|
+
switch(path.options.access.toLowerCase()){
|
|
45
|
+
case "private":
|
|
46
|
+
serveOptions.private.push(name);
|
|
47
|
+
break;
|
|
48
|
+
case "protected":
|
|
49
|
+
serveOptions.protected.push(name);
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
filter.add(model, {
|
|
55
|
+
filteredKeys: {
|
|
56
|
+
private: serveOptions.private,
|
|
57
|
+
protected: serveOptions.protected
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
const ops = operations(model, serveOptions, filter);
|
|
61
|
+
let uriItem = `${serveOptions.prefix}${serveOptions.version}/${serveOptions.name}`;
|
|
62
|
+
if (uriItem.indexOf("/:id") === -1) {
|
|
63
|
+
uriItem += "/:id";
|
|
64
|
+
}
|
|
65
|
+
const uriItems = uriItem.replace("/:id", "");
|
|
66
|
+
const uriCount = uriItems + "/count";
|
|
67
|
+
const uriShallow = uriItem + "/shallow";
|
|
68
|
+
if (typeof app.delete === "undefined") {
|
|
69
|
+
// @ts-expect-error restify
|
|
70
|
+
app.delete = app.del;
|
|
71
|
+
}
|
|
72
|
+
app.use((req, res, next)=>{
|
|
73
|
+
req.erm = {};
|
|
74
|
+
next();
|
|
75
|
+
});
|
|
76
|
+
const accessMiddleware = serveOptions.access ? getAccessHandler({
|
|
77
|
+
access: serveOptions.access,
|
|
78
|
+
idProperty: serveOptions.idProperty,
|
|
79
|
+
onError: serveOptions.onError
|
|
80
|
+
}) : [];
|
|
81
|
+
const ensureContentType = getEnsureContentTypeHandler(serveOptions);
|
|
82
|
+
const filterAndFindById = getFilterAndFindByIdHandler(serveOptions, model);
|
|
83
|
+
const prepareQuery = getPrepareQueryHandler(serveOptions);
|
|
84
|
+
const prepareOutput = getPrepareOutputHandler(serveOptions, model.modelName, filter);
|
|
85
|
+
app.get(uriItems, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getItems, prepareOutput);
|
|
86
|
+
app.get(uriCount, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getCount, prepareOutput);
|
|
87
|
+
app.get(uriItem, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getItem, prepareOutput);
|
|
88
|
+
app.get(uriShallow, prepareQuery, serveOptions.preMiddleware, serveOptions.preRead, accessMiddleware, ops.getShallow, prepareOutput);
|
|
89
|
+
app.post(uriItems, prepareQuery, ensureContentType, serveOptions.preMiddleware, serveOptions.preCreate, accessMiddleware, ops.createObject, prepareOutput);
|
|
90
|
+
app.post(uriItem, 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);
|
|
91
|
+
app.put(uriItem, 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);
|
|
92
|
+
app.patch(uriItem, prepareQuery, ensureContentType, serveOptions.preMiddleware, serveOptions.findOneAndUpdate ? [] : filterAndFindById, serveOptions.preUpdate, accessMiddleware, ops.modifyObject, prepareOutput);
|
|
93
|
+
app.delete(uriItems, prepareQuery, serveOptions.preMiddleware, serveOptions.preDelete, ops.deleteItems, prepareOutput);
|
|
94
|
+
app.delete(uriItem, prepareQuery, serveOptions.preMiddleware, serveOptions.findOneAndRemove ? [] : filterAndFindById, serveOptions.preDelete, ops.deleteItem, prepareOutput);
|
|
95
|
+
return uriItems;
|
|
96
|
+
}
|
|
@@ -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
|
+
}
|
package/dist/moredots.js
ADDED
|
@@ -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
|
+
}
|