@mingjue8888/express-plus 0.0.0-stage → 1.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 +149 -2
- package/async-middleware.ts +36 -0
- package/catch-crawler-response-error.ts +7 -0
- package/has-login.ts +7 -0
- package/has-permissions.ts +15 -0
- package/has-roles.ts +12 -0
- package/id-generator.ts +5 -0
- package/index.ts +209 -0
- package/login-account.ts +11 -0
- package/login-token.ts +7 -0
- package/not-found-response-error.ts +7 -0
- package/package.json +23 -4
- package/password-encoder.ts +9 -0
- package/permission-denied-response-error.ts +7 -0
- package/rbac0.ts +9 -0
- package/response-error.ts +9 -0
- package/router.ts +18 -0
- package/server-error-response-error.ts +7 -0
- package/too-many-requests-response-error.ts +7 -0
- package/tsconfig.json +16 -0
- package/unauthorized-response-error.ts +7 -0
- package/valid-body.ts +16 -0
- package/valid-param.ts +16 -0
- package/valid-query.ts +16 -0
- package/valid-response.ts +16 -0
- package/wrong-params-response-error.ts +7 -0
package/README.md
CHANGED
|
@@ -1,3 +1,150 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Usage
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## Define User
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
import LoginAccount from "@mingjue8888/express-plus/login-account";
|
|
7
|
+
|
|
8
|
+
export interface UserAccount extends LoginAccount {}
|
|
9
|
+
|
|
10
|
+
declare global {
|
|
11
|
+
namespace Express {
|
|
12
|
+
interface User extends UserAccount {}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Define Error
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
export class NotFoundUserError extends Error {}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Write Router
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import Joi from "joi";
|
|
27
|
+
import asyncMiddleware from "@mingjue8888/express-plus/async-middleware";
|
|
28
|
+
import hasLogin from "@mingjue8888/express-plus/has-login";
|
|
29
|
+
import Router from "@mingjue8888/express-plus/router";
|
|
30
|
+
import validBody from "@mingjue8888/express-plus/valid-body";
|
|
31
|
+
import validParam from "@mingjue8888/express-plus/valid-param";
|
|
32
|
+
import validResponse from "@mingjue8888/express-plus/valid-response";
|
|
33
|
+
|
|
34
|
+
// File ./routers/routerA.ts
|
|
35
|
+
const login: Router = {
|
|
36
|
+
method: "POST",
|
|
37
|
+
path: "/login",
|
|
38
|
+
middlewares: [
|
|
39
|
+
validBody({
|
|
40
|
+
username: Joi.string()
|
|
41
|
+
.required(),
|
|
42
|
+
|
|
43
|
+
password: Joi.string()
|
|
44
|
+
.regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/)
|
|
45
|
+
.required()
|
|
46
|
+
}),
|
|
47
|
+
asyncMiddleware(async function (req, res) {
|
|
48
|
+
const username = req.valid.body.username as string;
|
|
49
|
+
const password = req.valid.body.password as string;
|
|
50
|
+
const id = "UUID";
|
|
51
|
+
res.signToken(id);
|
|
52
|
+
}),
|
|
53
|
+
validResponse({
|
|
54
|
+
accessToken: Joi.string()
|
|
55
|
+
.required(),
|
|
56
|
+
}),
|
|
57
|
+
],
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export default [
|
|
61
|
+
login,
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
// File ./routers/routerB.ts
|
|
65
|
+
const findUser: Router = {
|
|
66
|
+
method: "GET",
|
|
67
|
+
path: "/users/:userId",
|
|
68
|
+
middlewares: [
|
|
69
|
+
hasLogin,
|
|
70
|
+
validParam({
|
|
71
|
+
userId: Joi.string()
|
|
72
|
+
.required(),
|
|
73
|
+
}),
|
|
74
|
+
asyncMiddleware(async function (req, res) {
|
|
75
|
+
throw new NotFoundUserError();
|
|
76
|
+
}),
|
|
77
|
+
validResponse({
|
|
78
|
+
id: Joi.string()
|
|
79
|
+
.required(),
|
|
80
|
+
|
|
81
|
+
name: Joi.string()
|
|
82
|
+
.required(),
|
|
83
|
+
}),
|
|
84
|
+
],
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const findUserPosts: Router = {
|
|
88
|
+
method: "GET",
|
|
89
|
+
path: "/users/:userId/posts",
|
|
90
|
+
middlewares: [
|
|
91
|
+
hasLogin,
|
|
92
|
+
validParam({
|
|
93
|
+
userId: Joi.string()
|
|
94
|
+
.required(),
|
|
95
|
+
}),
|
|
96
|
+
asyncMiddleware(async function (req, res) {
|
|
97
|
+
res.body = {
|
|
98
|
+
posts: []
|
|
99
|
+
}
|
|
100
|
+
}),
|
|
101
|
+
validResponse({
|
|
102
|
+
posts: Joi.array().items(Joi.object().keys({
|
|
103
|
+
id: Joi.string().required(),
|
|
104
|
+
content: Joi.string().required().default(""),
|
|
105
|
+
}))
|
|
106
|
+
})
|
|
107
|
+
],
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export default [
|
|
111
|
+
findUser,
|
|
112
|
+
findUserPosts,
|
|
113
|
+
];
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Start app
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
import app from "@mingjue8888/express-plus";
|
|
120
|
+
import routerA from "./routers/routerA";
|
|
121
|
+
import routerB from "./routers/routerB";
|
|
122
|
+
import {NotFoundUserError} from "./errors";
|
|
123
|
+
import NotFoundResponseError from "@mingjue8888/express-plus/not-found-response-error";
|
|
124
|
+
|
|
125
|
+
const routers = [
|
|
126
|
+
routerA,
|
|
127
|
+
routerB,
|
|
128
|
+
];
|
|
129
|
+
|
|
130
|
+
app(routers, {
|
|
131
|
+
APP_PORT: 3000,
|
|
132
|
+
|
|
133
|
+
async authenticate<UserAccount>(token: LoginToken) {
|
|
134
|
+
return {
|
|
135
|
+
id: token.sub,
|
|
136
|
+
isLocked: false,
|
|
137
|
+
isSuspended: false,
|
|
138
|
+
isBanned: false,
|
|
139
|
+
roles: [],
|
|
140
|
+
} as UserAccount;
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
// Covert Error to ResponseError
|
|
144
|
+
onError(err: Error) {
|
|
145
|
+
if (err instanceof NotFoundUserError) {
|
|
146
|
+
return new NotFoundResponseError(err.constructor.name, "Not found user");
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
```
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ErrorRequestHandler,
|
|
3
|
+
Handler,
|
|
4
|
+
NextFunction,
|
|
5
|
+
Request,
|
|
6
|
+
RequestHandler,
|
|
7
|
+
Response
|
|
8
|
+
} from "express";
|
|
9
|
+
|
|
10
|
+
declare global {
|
|
11
|
+
namespace Express {
|
|
12
|
+
interface Request {
|
|
13
|
+
valid: {
|
|
14
|
+
param: any;
|
|
15
|
+
query: any;
|
|
16
|
+
body: any;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type Middleware =
|
|
23
|
+
| Handler
|
|
24
|
+
| RequestHandler
|
|
25
|
+
| ErrorRequestHandler;
|
|
26
|
+
|
|
27
|
+
export type AsyncMiddlewareHandler =
|
|
28
|
+
(req: Request, res: Response) => Promise<void>;
|
|
29
|
+
|
|
30
|
+
export default function asyncMiddleware(handler: AsyncMiddlewareHandler): Middleware {
|
|
31
|
+
return function (req: Request, res: Response, next: NextFunction) {
|
|
32
|
+
handler(req, res)
|
|
33
|
+
.then(() => next())
|
|
34
|
+
.catch(err => next(err));
|
|
35
|
+
}
|
|
36
|
+
}
|
package/has-login.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import _ from "lodash";
|
|
2
|
+
import asyncMiddleware, {Middleware} from "./async-middleware";
|
|
3
|
+
import PermissionDeniedResponseError from "./permission-denied-response-error";
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
export default function hasPermissions(permissions: string[]): Middleware {
|
|
7
|
+
return asyncMiddleware(async function (req, _res) {
|
|
8
|
+
const userPermissions = req.user?.roles
|
|
9
|
+
.map(r => r.permissions)
|
|
10
|
+
.flat();
|
|
11
|
+
|
|
12
|
+
const noPermission = _.intersection(permissions, userPermissions).length === 0;
|
|
13
|
+
if (noPermission) throw new PermissionDeniedResponseError("PermissionDeniedError", "You do not have permission");
|
|
14
|
+
});
|
|
15
|
+
}
|
package/has-roles.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import _ from "lodash";
|
|
2
|
+
import asyncMiddleware, {Middleware} from "./async-middleware";
|
|
3
|
+
import PermissionDeniedResponseError from "./permission-denied-response-error";
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
export default function hasRoles(roles: string[]): Middleware {
|
|
7
|
+
return asyncMiddleware(async function (req, _res) {
|
|
8
|
+
const userRoles = req.user?.roles.map(r => r.name);
|
|
9
|
+
const noRole = _.intersection(roles, userRoles).length === 0;
|
|
10
|
+
if (noRole) throw new PermissionDeniedResponseError("NotQualifiedError", "You do not meet the qualifications");
|
|
11
|
+
});
|
|
12
|
+
}
|
package/id-generator.ts
ADDED
package/index.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import logger from "@mingjue8888/base-dependencies/logger";
|
|
3
|
+
import compression from "compression";
|
|
4
|
+
import cors from "cors";
|
|
5
|
+
import express from "express";
|
|
6
|
+
import rateLimit from "express-rate-limit";
|
|
7
|
+
import Joi from "joi";
|
|
8
|
+
import jwt from "jsonwebtoken";
|
|
9
|
+
import _ from "lodash";
|
|
10
|
+
import morgan from "morgan";
|
|
11
|
+
import passport from "passport";
|
|
12
|
+
import {ExtractJwt, Strategy, StrategyOptions} from "passport-jwt";
|
|
13
|
+
import {Middleware} from "./async-middleware";
|
|
14
|
+
import LoginAccount from "./login-account";
|
|
15
|
+
import LoginToken from "./login-token";
|
|
16
|
+
import PermissionDeniedResponseError from "./permission-denied-response-error";
|
|
17
|
+
import ResponseError from "./response-error";
|
|
18
|
+
import Router from "./router";
|
|
19
|
+
import ServerErrorResponseError from "./server-error-response-error";
|
|
20
|
+
import TooManyRequestsResponseError from "./too-many-requests-response-error";
|
|
21
|
+
import UnauthorizedResponseError from "./unauthorized-response-error";
|
|
22
|
+
|
|
23
|
+
type DeepArray<T> =
|
|
24
|
+
| T[]
|
|
25
|
+
| DeepArray<T>[];
|
|
26
|
+
|
|
27
|
+
type ResponseErrorConverter =
|
|
28
|
+
(err: Error) => ResponseError | void;
|
|
29
|
+
|
|
30
|
+
function errorConverter(onError?: ResponseErrorConverter): Middleware {
|
|
31
|
+
return function (
|
|
32
|
+
err: Error,
|
|
33
|
+
_req: express.Request,
|
|
34
|
+
_res: express.Response,
|
|
35
|
+
next: express.NextFunction
|
|
36
|
+
) {
|
|
37
|
+
if (onError) {
|
|
38
|
+
const resErr = onError(err);
|
|
39
|
+
if (resErr) {
|
|
40
|
+
next(onError(err));
|
|
41
|
+
} else {
|
|
42
|
+
next(err);
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
next(err);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function errorHandler(
|
|
51
|
+
err: Error,
|
|
52
|
+
_req: express.Request,
|
|
53
|
+
res: express.Response,
|
|
54
|
+
_next: express.NextFunction
|
|
55
|
+
) {
|
|
56
|
+
if (err instanceof ResponseError) {
|
|
57
|
+
res
|
|
58
|
+
.status(err.getHttpResponseStatus())
|
|
59
|
+
.send({ error: err.error, message: err.message });
|
|
60
|
+
} else {
|
|
61
|
+
logger.error(err);
|
|
62
|
+
res
|
|
63
|
+
.status(500)
|
|
64
|
+
.send({ error: "ServerError", message: err.stack });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
declare global {
|
|
69
|
+
namespace Express {
|
|
70
|
+
interface User extends LoginAccount {}
|
|
71
|
+
interface Response {
|
|
72
|
+
signToken: (sub: string) => void;
|
|
73
|
+
body?: any;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface EnvOptions {
|
|
79
|
+
APP_PORT?: number;
|
|
80
|
+
APP_REQUEST_RATE_LIMIT?: number;
|
|
81
|
+
APP_REQUEST_RATE_LIMIT_RANGE?: number;
|
|
82
|
+
APP_CORS_ALLOW_ORIGIN?: string;
|
|
83
|
+
JWT_SECRET?: string;
|
|
84
|
+
JWT_EXPIRE?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface StartupOptions extends EnvOptions {
|
|
88
|
+
authenticate?: <T extends LoginAccount>(token: LoginToken) => Promise<T>;
|
|
89
|
+
onError?: ResponseErrorConverter;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const oneSecond = 1000;
|
|
93
|
+
const oneMinute = oneSecond * 60;
|
|
94
|
+
const oneHour = oneMinute * 60;
|
|
95
|
+
const oneDay = oneHour * 24;
|
|
96
|
+
|
|
97
|
+
const optSchema = Joi.object<Required<StartupOptions>, StartupOptions>({
|
|
98
|
+
APP_PORT: Joi.number()
|
|
99
|
+
.integer()
|
|
100
|
+
.required()
|
|
101
|
+
.default(8086),
|
|
102
|
+
|
|
103
|
+
APP_REQUEST_RATE_LIMIT: Joi.number()
|
|
104
|
+
.required()
|
|
105
|
+
.default(20),
|
|
106
|
+
|
|
107
|
+
APP_REQUEST_RATE_LIMIT_RANGE: Joi.number()
|
|
108
|
+
.required()
|
|
109
|
+
.default(oneSecond),
|
|
110
|
+
|
|
111
|
+
APP_CORS_ALLOW_ORIGIN: Joi.string()
|
|
112
|
+
.required()
|
|
113
|
+
.default("*"),
|
|
114
|
+
|
|
115
|
+
JWT_SECRET: Joi.string()
|
|
116
|
+
.required()
|
|
117
|
+
.default("DefaultSecret"),
|
|
118
|
+
|
|
119
|
+
JWT_EXPIRE: Joi.number()
|
|
120
|
+
.integer()
|
|
121
|
+
.greater(0)
|
|
122
|
+
.when("JWT_SECRET", {
|
|
123
|
+
is: Joi.exist(),
|
|
124
|
+
then: Joi.required()
|
|
125
|
+
.default(oneDay * 7)
|
|
126
|
+
}),
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
export default function app(routers: DeepArray<Router>, opt?: StartupOptions) {
|
|
130
|
+
if (opt) {
|
|
131
|
+
Reflect.ownKeys(process.env)
|
|
132
|
+
.filter(key => key === key.toString().toUpperCase())
|
|
133
|
+
.forEach(key => Reflect.set(opt, key, process.env[key as string]));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const conf: Required<StartupOptions> =
|
|
137
|
+
Joi.attempt(opt || {}, optSchema, { allowUnknown: true });
|
|
138
|
+
|
|
139
|
+
const jwtStrategy: StrategyOptions = {
|
|
140
|
+
secretOrKey: conf.JWT_SECRET,
|
|
141
|
+
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
142
|
+
ignoreExpiration: true,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const strategy = new Strategy(jwtStrategy, function (payload: LoginToken, next) {
|
|
146
|
+
if (!opt?.authenticate) {
|
|
147
|
+
next(new ServerErrorResponseError("AuthenticationError", "Missing authentication logic"), false);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const isExpired = (exp: number): boolean =>
|
|
151
|
+
exp < Math.floor(Date.now() / 1000);
|
|
152
|
+
|
|
153
|
+
if (isExpired(payload.exp)) {
|
|
154
|
+
next(new UnauthorizedResponseError("TokenExpiredError", "The token has expired"), false);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
opt.authenticate(payload)
|
|
159
|
+
.then(user => user.isLocked ? Promise.reject(new PermissionDeniedResponseError("AccountLockedError", "Your account has been locked")) : user)
|
|
160
|
+
.then(user => user.isSuspended ? Promise.reject(new PermissionDeniedResponseError("AccountSuspendedError", "Your account is disabled")) : user)
|
|
161
|
+
.then(user => user.isBanned ? Promise.reject(new PermissionDeniedResponseError("AccountBannedError", "Your account has been permanently banned")) : user)
|
|
162
|
+
.then(user => next(null, user))
|
|
163
|
+
.catch(err => next(err, false));
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
passport.use(strategy);
|
|
167
|
+
|
|
168
|
+
function addSignToken(_req: express.Request, res: express.Response, next: express.NextFunction) {
|
|
169
|
+
const now = Math.floor(Date.now() /1000);
|
|
170
|
+
res.signToken = (sub: string) => {
|
|
171
|
+
const payload = {
|
|
172
|
+
sub,
|
|
173
|
+
iat: now,
|
|
174
|
+
exp: now + conf.JWT_EXPIRE
|
|
175
|
+
};
|
|
176
|
+
const accessToken = jwt.sign(payload, conf.JWT_SECRET);
|
|
177
|
+
res.body = { accessToken };
|
|
178
|
+
}
|
|
179
|
+
next();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const routes = _.flattenDeep(routers).reduce(
|
|
183
|
+
(router: express.Router, route: Router): express.Router =>
|
|
184
|
+
Reflect.get(router, route.path.toLowerCase()).bind(router)(route.path, ...route.middlewares),
|
|
185
|
+
express.Router(),
|
|
186
|
+
);
|
|
187
|
+
|
|
188
|
+
return express()
|
|
189
|
+
.use(rateLimit({
|
|
190
|
+
windowMs: conf.APP_REQUEST_RATE_LIMIT_RANGE, limit: conf.APP_REQUEST_RATE_LIMIT,
|
|
191
|
+
handler: (_req, _res, next) =>
|
|
192
|
+
next(new TooManyRequestsResponseError("TooManyRequests", "Too many requests, please try again later"))
|
|
193
|
+
}))
|
|
194
|
+
.use(cors({ origin: conf.APP_CORS_ALLOW_ORIGIN }))
|
|
195
|
+
.use(morgan(":method :url :status :res[content-length] - :response-time ms", {
|
|
196
|
+
stream: {
|
|
197
|
+
write: message => logger.http(message.trim())
|
|
198
|
+
}
|
|
199
|
+
}))
|
|
200
|
+
.use(compression())
|
|
201
|
+
.use(express.urlencoded({ extended: true }))
|
|
202
|
+
.use(express.json())
|
|
203
|
+
.use(passport.initialize())
|
|
204
|
+
.use(addSignToken)
|
|
205
|
+
.use(routes)
|
|
206
|
+
.use(errorConverter(opt?.onError))
|
|
207
|
+
.use(errorHandler)
|
|
208
|
+
.listen(conf.APP_PORT, () => logger.info(`Server startup on port: ${conf.APP_PORT}`));
|
|
209
|
+
}
|
package/login-account.ts
ADDED
package/login-token.ts
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mingjue8888/express-plus",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"repository": "github:mingjue8888/express-plus",
|
|
5
|
+
"dependencies": {
|
|
6
|
+
"@mingjue8888/base-dependencies": "^1.1.0",
|
|
7
|
+
"bcrypt": "^6.0.0",
|
|
8
|
+
"compression": "^1.8.2",
|
|
9
|
+
"cors": "^2.8.6",
|
|
10
|
+
"express-rate-limit": "^8.7.4",
|
|
11
|
+
"jsonwebtoken": "^9.0.3",
|
|
12
|
+
"morgan": "^1.12.1",
|
|
13
|
+
"passport": "^0.7.0",
|
|
14
|
+
"passport-jwt": "^4.0.1"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@types/bcrypt": "^6.0.0",
|
|
18
|
+
"@types/compression": "^1.8.1",
|
|
19
|
+
"@types/cors": "^2.8.19",
|
|
20
|
+
"@types/express": "^5.0.6",
|
|
21
|
+
"@types/morgan": "^1.9.10",
|
|
22
|
+
"@types/passport": "^1.0.17",
|
|
23
|
+
"@types/passport-jwt": "^4.0.1"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import bcrypt from "bcrypt";
|
|
2
|
+
|
|
3
|
+
export function encode(password: string): string {
|
|
4
|
+
return bcrypt.hashSync(password, bcrypt.genSaltSync());
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function check(password: string, encoded: string): boolean {
|
|
8
|
+
return bcrypt.compareSync(password, encoded);
|
|
9
|
+
}
|
package/rbac0.ts
ADDED
package/router.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import {Middleware} from "./async-middleware";
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
type Method =
|
|
5
|
+
| "GET"
|
|
6
|
+
| "POST"
|
|
7
|
+
| "PUT"
|
|
8
|
+
| "DELETE";
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
type Path =
|
|
12
|
+
string;
|
|
13
|
+
|
|
14
|
+
export default interface Router {
|
|
15
|
+
method: Method,
|
|
16
|
+
path: Path,
|
|
17
|
+
middlewares: Middleware[];
|
|
18
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"allowArbitraryExtensions": true,
|
|
4
|
+
"allowSyntheticDefaultImports": true,
|
|
5
|
+
"alwaysStrict": true,
|
|
6
|
+
"esModuleInterop": true,
|
|
7
|
+
"forceConsistentCasingInFileNames": true,
|
|
8
|
+
"module": "esnext",
|
|
9
|
+
"moduleResolution": "node",
|
|
10
|
+
"noImplicitAny": false,
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"strict": true,
|
|
13
|
+
"target": "esnext",
|
|
14
|
+
"useUnknownInCatchVariables": true
|
|
15
|
+
}
|
|
16
|
+
}
|
package/valid-body.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import Joi from "joi";
|
|
2
|
+
import asyncMiddleware from "./async-middleware";
|
|
3
|
+
import WrongParamsResponseError from "./wrong-params-response-error";
|
|
4
|
+
|
|
5
|
+
export default function validBody(sch: Record<string, Joi.AnySchema>) {
|
|
6
|
+
return asyncMiddleware(async function (req, _res) {
|
|
7
|
+
const { error, value } = Joi
|
|
8
|
+
.object(sch)
|
|
9
|
+
.validate(req.body, { allowUnknown: true });
|
|
10
|
+
|
|
11
|
+
if (error) {
|
|
12
|
+
throw new WrongParamsResponseError("WrongParamsError", error.message);
|
|
13
|
+
}
|
|
14
|
+
req.valid.body = value;
|
|
15
|
+
});
|
|
16
|
+
}
|
package/valid-param.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import Joi from "joi";
|
|
2
|
+
import asyncMiddleware from "./async-middleware";
|
|
3
|
+
import WrongParamsResponseError from "./wrong-params-response-error";
|
|
4
|
+
|
|
5
|
+
export default function validParam(sch: Record<string, Joi.AnySchema>) {
|
|
6
|
+
return asyncMiddleware(async function (req, _res) {
|
|
7
|
+
const { error, value } = Joi
|
|
8
|
+
.object(sch)
|
|
9
|
+
.validate(req.params, { allowUnknown: true });
|
|
10
|
+
|
|
11
|
+
if (error) {
|
|
12
|
+
throw new WrongParamsResponseError("WrongParamsError", error.message);
|
|
13
|
+
}
|
|
14
|
+
req.valid.param = value;
|
|
15
|
+
});
|
|
16
|
+
}
|
package/valid-query.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import Joi from "joi";
|
|
2
|
+
import asyncMiddleware from "./async-middleware";
|
|
3
|
+
import WrongParamsResponseError from "./wrong-params-response-error";
|
|
4
|
+
|
|
5
|
+
export default function validQuery(sch: Record<string, Joi.AnySchema>) {
|
|
6
|
+
return asyncMiddleware(async function (req, _res) {
|
|
7
|
+
const { error, value } = Joi
|
|
8
|
+
.object(sch)
|
|
9
|
+
.validate(req.query, { allowUnknown: true });
|
|
10
|
+
|
|
11
|
+
if (error) {
|
|
12
|
+
throw new WrongParamsResponseError("WrongParamsError", error.message);
|
|
13
|
+
}
|
|
14
|
+
req.valid.query = value;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import Joi from "joi";
|
|
2
|
+
import asyncMiddleware from "./async-middleware";
|
|
3
|
+
import ServerErrorResponseError from "./server-error-response-error";
|
|
4
|
+
|
|
5
|
+
export default function validResponse(sch: Record<string, Joi.AnySchema>) {
|
|
6
|
+
return asyncMiddleware(async function (_req, res) {
|
|
7
|
+
const { error, value } = Joi
|
|
8
|
+
.object(sch)
|
|
9
|
+
.validate(res.body);
|
|
10
|
+
|
|
11
|
+
if (error) {
|
|
12
|
+
throw new ServerErrorResponseError("WrongResponseError", error.message);
|
|
13
|
+
}
|
|
14
|
+
res.status(200).send(value);
|
|
15
|
+
});
|
|
16
|
+
}
|