equipped 4.4.6 → 5.0.0-beta-2
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/CHANGELOG.md +32 -0
- package/lib/db/_instance.d.ts +3 -6
- package/lib/db/mongoose/changes.d.ts +2 -1
- package/lib/db/mongoose/index.d.ts +2 -1
- package/lib/db/mongoose/index.js +3 -1
- package/lib/db/mongoose/query.d.ts +1 -0
- package/lib/db/query.d.ts +12 -11
- package/lib/errors/customError.d.ts +0 -1
- package/lib/errors/customError.js +0 -1
- package/lib/errors/index.d.ts +0 -2
- package/lib/errors/index.js +0 -2
- package/lib/errors/types/refreshTokenMisusedError.d.ts +1 -1
- package/lib/errors/types/refreshTokenMisusedError.js +1 -1
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -0
- package/lib/instance/index.d.ts +5 -4
- package/lib/instance/index.js +17 -4
- package/lib/instance/settings.d.ts +8 -0
- package/lib/instance/settings.js +7 -1
- package/lib/listeners/emitter.d.ts +3 -3
- package/lib/scripts/index.d.ts +1 -0
- package/lib/scripts/index.js +17 -0
- package/lib/scripts/json-schema.d.ts +2 -0
- package/lib/scripts/json-schema.js +75 -0
- package/lib/server/impls/base.d.ts +37 -0
- package/lib/server/impls/base.js +120 -0
- package/lib/server/impls/express.d.ts +16 -0
- package/lib/server/impls/express.js +183 -0
- package/lib/server/impls/fastify.d.ts +23 -0
- package/lib/server/impls/fastify.js +182 -0
- package/lib/server/index.d.ts +7 -6
- package/lib/server/index.js +10 -8
- package/lib/server/middlewares/errorHandler.d.ts +4 -1
- package/lib/server/middlewares/errorHandler.js +10 -11
- package/lib/server/middlewares/index.d.ts +1 -0
- package/lib/server/middlewares/index.js +1 -0
- package/lib/server/middlewares/notFoundHandler.d.ts +4 -1
- package/lib/server/middlewares/notFoundHandler.js +3 -3
- package/lib/server/middlewares/parseAuthUser.d.ts +4 -1
- package/lib/server/middlewares/parseAuthUser.js +2 -2
- package/lib/server/middlewares/requireAuthUser.d.ts +4 -2
- package/lib/server/middlewares/requireAuthUser.js +8 -3
- package/lib/server/middlewares/requireRefreshUser.d.ts +4 -2
- package/lib/server/middlewares/requireRefreshUser.js +7 -4
- package/lib/server/requests.d.ts +50 -0
- package/lib/server/requests.js +60 -0
- package/lib/server/routes.d.ts +6 -23
- package/lib/server/routes.js +39 -49
- package/lib/server/types.d.ts +85 -0
- package/lib/server/types.js +33 -0
- package/lib/structure/baseEntity.d.ts +4 -5
- package/lib/structure/baseEntity.js +20 -12
- package/lib/types/index.d.ts +20 -0
- package/lib/types/index.js +2 -0
- package/lib/validations/index.d.ts +1 -1
- package/package.json +36 -22
- package/lib/errors/types/accountNotVerifiedError.d.ts +0 -5
- package/lib/errors/types/accountNotVerifiedError.js +0 -12
- package/lib/errors/types/invalidToken.d.ts +0 -5
- package/lib/errors/types/invalidToken.js +0 -12
- package/lib/logger/index.d.ts +0 -13
- package/lib/logger/index.js +0 -41
- package/lib/server/app.d.ts +0 -12
- package/lib/server/app.js +0 -121
- package/lib/server/controllers/index.d.ts +0 -10
- package/lib/server/controllers/index.js +0 -46
- package/lib/server/controllers/request.d.ts +0 -40
- package/lib/server/controllers/request.js +0 -85
- package/lib/server/controllers/response.d.ts +0 -14
- package/lib/server/controllers/response.js +0 -16
- package/lib/server/statusCodes.d.ts +0 -16
- package/lib/server/statusCodes.js +0 -17
|
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.parseAuthUser = void 0;
|
|
4
4
|
const errors_1 = require("../../errors");
|
|
5
5
|
const tokens_1 = require("../../utils/tokens");
|
|
6
|
-
const
|
|
7
|
-
exports.parseAuthUser = (0,
|
|
6
|
+
const types_1 = require("../types");
|
|
7
|
+
exports.parseAuthUser = (0, types_1.makeMiddleware)(async (request) => {
|
|
8
8
|
const accessToken = request.headers.AccessToken;
|
|
9
9
|
if (accessToken)
|
|
10
10
|
request.authUser = await (0, tokens_1.verifyAccessToken)(accessToken).catch((err) => {
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
export declare const requireAuthUser: {
|
|
2
|
+
cb: import("../types").RouteMiddlewareHandler<import("../types").Api<unknown, string, import("../types").MethodTypes, unknown, unknown, unknown, import("../types").SupportedStatusCodes>>;
|
|
3
|
+
onSetup?: import("../types").HandlerSetup | undefined;
|
|
4
|
+
};
|
|
@@ -2,10 +2,15 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.requireAuthUser = void 0;
|
|
4
4
|
const errors_1 = require("../../errors");
|
|
5
|
-
const
|
|
5
|
+
const types_1 = require("../types");
|
|
6
|
+
exports.requireAuthUser = (0, types_1.makeMiddleware)(async (request) => {
|
|
6
7
|
if (request.pendingError)
|
|
7
8
|
throw request.pendingError;
|
|
9
|
+
if (!request.headers.AccessToken)
|
|
10
|
+
throw new errors_1.NotAuthenticatedError('Access-Token header missing');
|
|
8
11
|
if (!request.authUser)
|
|
9
12
|
throw new errors_1.NotAuthenticatedError();
|
|
10
|
-
}
|
|
11
|
-
|
|
13
|
+
}, (route) => {
|
|
14
|
+
route.security ?? (route.security = []);
|
|
15
|
+
route.security.push({ AccessToken: [] });
|
|
16
|
+
});
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
export declare const requireRefreshUser: {
|
|
2
|
+
cb: import("../types").RouteMiddlewareHandler<import("../types").Api<unknown, string, import("../types").MethodTypes, unknown, unknown, unknown, import("../types").SupportedStatusCodes>>;
|
|
3
|
+
onSetup?: import("../types").HandlerSetup | undefined;
|
|
4
|
+
};
|
|
@@ -3,12 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.requireRefreshUser = void 0;
|
|
4
4
|
const errors_1 = require("../../errors");
|
|
5
5
|
const tokens_1 = require("../../utils/tokens");
|
|
6
|
-
const
|
|
6
|
+
const types_1 = require("../types");
|
|
7
|
+
exports.requireRefreshUser = (0, types_1.makeMiddleware)(async (request) => {
|
|
7
8
|
const refreshToken = request.headers.RefreshToken;
|
|
8
9
|
if (!refreshToken)
|
|
9
|
-
throw new errors_1.NotAuthorizedError();
|
|
10
|
+
throw new errors_1.NotAuthorizedError('Refresh-Token header missing');
|
|
10
11
|
request.refreshUser = await (0, tokens_1.verifyRefreshToken)(refreshToken);
|
|
11
12
|
if (!request.refreshUser)
|
|
12
13
|
throw new errors_1.NotAuthorizedError();
|
|
13
|
-
}
|
|
14
|
-
|
|
14
|
+
}, (route) => {
|
|
15
|
+
route.security ?? (route.security = []);
|
|
16
|
+
route.security.push({ RefreshToken: [] });
|
|
17
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { Writable } from 'stream';
|
|
3
|
+
import { CustomError } from '../errors';
|
|
4
|
+
import { StorageFile } from '../storage';
|
|
5
|
+
import { AuthUser, RefreshUser } from '../utils/authUser';
|
|
6
|
+
import { Api, SupportedStatusCodes } from './types';
|
|
7
|
+
type HeaderKeys = 'AccessToken' | 'RefreshToken' | 'Referer' | 'ContentType' | 'UserAgent';
|
|
8
|
+
export declare class Request<Def extends Api = Api> {
|
|
9
|
+
#private;
|
|
10
|
+
private readonly response;
|
|
11
|
+
readonly ip: string | undefined;
|
|
12
|
+
readonly method: Def['method'];
|
|
13
|
+
readonly path: string;
|
|
14
|
+
readonly body: Def['body'];
|
|
15
|
+
readonly params: Def['params'];
|
|
16
|
+
readonly query: Def['query'];
|
|
17
|
+
readonly cookies: Record<string, any>;
|
|
18
|
+
readonly rawBody: unknown;
|
|
19
|
+
readonly headers: Record<HeaderKeys, string | null> & Record<string, string | string[] | null>;
|
|
20
|
+
readonly files: Record<string, StorageFile[]>;
|
|
21
|
+
authUser: null | AuthUser;
|
|
22
|
+
refreshUser: null | RefreshUser;
|
|
23
|
+
pendingError: null | CustomError;
|
|
24
|
+
constructor({ ip, body, cookies, params, query, method, path, headers, files }: {
|
|
25
|
+
ip: string | undefined;
|
|
26
|
+
body: unknown;
|
|
27
|
+
params: Def['params'];
|
|
28
|
+
query: Def['query'];
|
|
29
|
+
cookies: Record<string, any>;
|
|
30
|
+
headers: Record<HeaderKeys, string | null> & Record<string, string | string[] | null>;
|
|
31
|
+
files: Record<string, StorageFile[]>;
|
|
32
|
+
method: Def['method'];
|
|
33
|
+
path: string;
|
|
34
|
+
}, response: Writable);
|
|
35
|
+
pipe(cb: (stream: Writable) => void): Response<Writable, 200>;
|
|
36
|
+
}
|
|
37
|
+
export declare class Response<T, S extends SupportedStatusCodes = SupportedStatusCodes> {
|
|
38
|
+
readonly body: T | undefined;
|
|
39
|
+
readonly status: S;
|
|
40
|
+
readonly headers: Record<string, any>;
|
|
41
|
+
readonly piped: boolean;
|
|
42
|
+
constructor({ body, status, headers, piped }: {
|
|
43
|
+
body?: T;
|
|
44
|
+
status?: S;
|
|
45
|
+
headers?: Record<string, any>;
|
|
46
|
+
piped?: boolean;
|
|
47
|
+
});
|
|
48
|
+
get shouldJSONify(): boolean;
|
|
49
|
+
}
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
5
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6
|
+
};
|
|
7
|
+
var _Request_instances, _Request_parseQueryStrings;
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.Response = exports.Request = void 0;
|
|
10
|
+
const json_1 = require("../utils/json");
|
|
11
|
+
const types_1 = require("./types");
|
|
12
|
+
class Request {
|
|
13
|
+
constructor({ ip, body, cookies, params, query, method, path, headers, files }, response) {
|
|
14
|
+
_Request_instances.add(this);
|
|
15
|
+
this.response = response;
|
|
16
|
+
this.authUser = null;
|
|
17
|
+
this.refreshUser = null;
|
|
18
|
+
this.pendingError = null;
|
|
19
|
+
this.ip = ip;
|
|
20
|
+
this.method = method;
|
|
21
|
+
this.path = path;
|
|
22
|
+
this.rawBody = body;
|
|
23
|
+
this.body = Object.fromEntries(Object.entries(body && typeof body === 'object' ? body : { raw: body })
|
|
24
|
+
.map(([key, value]) => [key, (0, json_1.parseJSONValue)(value)]));
|
|
25
|
+
this.cookies = cookies;
|
|
26
|
+
this.params = params;
|
|
27
|
+
this.query = Object.fromEntries(Object.entries(query && typeof body === 'object' ? query : {})
|
|
28
|
+
.map(([key, val]) => [key, __classPrivateFieldGet(this, _Request_instances, "m", _Request_parseQueryStrings).call(this, val)]));
|
|
29
|
+
if (this.query?.['auth'])
|
|
30
|
+
delete this.query['auth'];
|
|
31
|
+
if (this.query?.['authType'])
|
|
32
|
+
delete this.query['authType'];
|
|
33
|
+
this.headers = headers;
|
|
34
|
+
this.files = files;
|
|
35
|
+
}
|
|
36
|
+
pipe(cb) {
|
|
37
|
+
cb(this.response);
|
|
38
|
+
return new Response({ piped: true, status: types_1.StatusCodes.Ok, body: this.response });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
exports.Request = Request;
|
|
42
|
+
_Request_instances = new WeakSet(), _Request_parseQueryStrings = function _Request_parseQueryStrings(value) {
|
|
43
|
+
if (Array.isArray(value))
|
|
44
|
+
return value.map(__classPrivateFieldGet(this, _Request_instances, "m", _Request_parseQueryStrings));
|
|
45
|
+
if (typeof value === 'string')
|
|
46
|
+
return (0, json_1.parseJSONValue)(value);
|
|
47
|
+
return value;
|
|
48
|
+
};
|
|
49
|
+
class Response {
|
|
50
|
+
constructor({ body, status = types_1.StatusCodes.Ok, headers = { 'Content-Type': 'application/json' }, piped = false }) {
|
|
51
|
+
this.body = body;
|
|
52
|
+
this.status = status;
|
|
53
|
+
this.headers = headers;
|
|
54
|
+
this.piped = piped;
|
|
55
|
+
}
|
|
56
|
+
get shouldJSONify() {
|
|
57
|
+
return this.body === null || this.body === undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
exports.Response = Response;
|
package/lib/server/routes.d.ts
CHANGED
|
@@ -1,26 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
export
|
|
4
|
-
|
|
5
|
-
method: MethodTypes;
|
|
6
|
-
controllers: Controller[];
|
|
7
|
-
global?: boolean;
|
|
8
|
-
};
|
|
9
|
-
export declare const formatPath: (path: string) => string;
|
|
10
|
-
export declare const groupRoutes: (parent: string, routes: Route[]) => Route[];
|
|
11
|
-
type RouteConfig = Partial<Omit<Route, 'method' | 'controllers'>> & {
|
|
12
|
-
middlewares?: Route['controllers'];
|
|
13
|
-
};
|
|
14
|
-
export declare class Router {
|
|
1
|
+
import { ClassPropertiesWrapper } from 'valleyed';
|
|
2
|
+
import { AddMethodImpls, GeneralConfig, Route } from './types';
|
|
3
|
+
export declare const groupRoutes: (config: GeneralConfig, routes: Route[]) => Route[];
|
|
4
|
+
export declare class Router extends ClassPropertiesWrapper<AddMethodImpls> {
|
|
15
5
|
#private;
|
|
16
|
-
|
|
17
|
-
constructor(config?: RouteConfig);
|
|
18
|
-
get(route: RouteConfig): <T>(handler?: RouteHandler<T> | undefined) => void;
|
|
19
|
-
post(route: RouteConfig): <T>(handler?: RouteHandler<T> | undefined) => void;
|
|
20
|
-
put(route: RouteConfig): <T>(handler?: RouteHandler<T> | undefined) => void;
|
|
21
|
-
patch(route: RouteConfig): <T>(handler?: RouteHandler<T> | undefined) => void;
|
|
22
|
-
delete(route: RouteConfig): <T>(handler?: RouteHandler<T> | undefined) => void;
|
|
23
|
-
all(route: RouteConfig): <T>(handler?: RouteHandler<T> | undefined) => void;
|
|
6
|
+
constructor(config?: GeneralConfig);
|
|
24
7
|
include(router: Router): void;
|
|
8
|
+
get routes(): Route[];
|
|
25
9
|
}
|
|
26
|
-
export {};
|
package/lib/server/routes.js
CHANGED
|
@@ -1,69 +1,59 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
5
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6
|
+
};
|
|
2
7
|
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
8
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
9
|
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
11
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
12
|
};
|
|
8
|
-
var
|
|
9
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
-
};
|
|
13
|
-
var _Router_instances, _Router_config, _Router_addRoute;
|
|
13
|
+
var _Router_instances, _Router_config, _Router_routes, _Router_children, _Router_addRoute;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.Router = exports.groupRoutes =
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
15
|
+
exports.Router = exports.groupRoutes = void 0;
|
|
16
|
+
const valleyed_1 = require("valleyed");
|
|
17
|
+
const types_1 = require("./types");
|
|
18
|
+
const groupRoutes = (config, routes) => routes
|
|
19
|
+
.map((route) => ({
|
|
20
|
+
...config,
|
|
21
|
+
...route,
|
|
22
|
+
path: `${config.path}/${route.path}`,
|
|
23
|
+
tags: [...(config.tags ?? []), ...(route.tags ?? [])],
|
|
24
|
+
middlewares: [...(config.middlewares ?? []), ...(route.middlewares ?? [])],
|
|
25
|
+
security: [...(config.security ?? []), ...(route.security ?? [])],
|
|
26
|
+
}));
|
|
23
27
|
exports.groupRoutes = groupRoutes;
|
|
24
|
-
class Router {
|
|
28
|
+
class Router extends valleyed_1.ClassPropertiesWrapper {
|
|
25
29
|
constructor(config) {
|
|
30
|
+
const methodImpls = Object.fromEntries(Object.values(types_1.Methods).map((method) => [method, (route) => __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, method, route)]));
|
|
31
|
+
super(methodImpls);
|
|
26
32
|
_Router_instances.add(this);
|
|
27
|
-
_Router_config.set(this,
|
|
28
|
-
this
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, 'get', route);
|
|
33
|
-
}
|
|
34
|
-
post(route) {
|
|
35
|
-
return __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, 'post', route);
|
|
36
|
-
}
|
|
37
|
-
put(route) {
|
|
38
|
-
return __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, 'put', route);
|
|
39
|
-
}
|
|
40
|
-
patch(route) {
|
|
41
|
-
return __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, 'patch', route);
|
|
42
|
-
}
|
|
43
|
-
delete(route) {
|
|
44
|
-
return __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, 'delete', route);
|
|
45
|
-
}
|
|
46
|
-
all(route) {
|
|
47
|
-
return __classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, 'all', route);
|
|
33
|
+
_Router_config.set(this, { path: '' });
|
|
34
|
+
_Router_routes.set(this, []);
|
|
35
|
+
_Router_children.set(this, []);
|
|
36
|
+
if (config)
|
|
37
|
+
__classPrivateFieldSet(this, _Router_config, config, "f");
|
|
48
38
|
}
|
|
49
39
|
include(router) {
|
|
50
|
-
|
|
51
|
-
|
|
40
|
+
__classPrivateFieldGet(this, _Router_children, "f").push(router);
|
|
41
|
+
}
|
|
42
|
+
get routes() {
|
|
43
|
+
const routes = __classPrivateFieldGet(this, _Router_routes, "f");
|
|
44
|
+
__classPrivateFieldGet(this, _Router_children, "f").forEach((child) => {
|
|
45
|
+
child.routes.forEach((route) => {
|
|
46
|
+
__classPrivateFieldGet(this, _Router_instances, "m", _Router_addRoute).call(this, route.method, route, routes)(route.handler);
|
|
47
|
+
});
|
|
52
48
|
});
|
|
49
|
+
return routes;
|
|
53
50
|
}
|
|
54
51
|
}
|
|
55
52
|
exports.Router = Router;
|
|
56
|
-
_Router_config = new WeakMap(), _Router_instances = new WeakSet(), _Router_addRoute = function _Router_addRoute(method,
|
|
53
|
+
_Router_config = new WeakMap(), _Router_routes = new WeakMap(), _Router_children = new WeakMap(), _Router_instances = new WeakSet(), _Router_addRoute = function _Router_addRoute(method, routeConfig, collection = __classPrivateFieldGet(this, _Router_routes, "f")) {
|
|
57
54
|
return (handler) => {
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
this.routes.push({
|
|
62
|
-
...__classPrivateFieldGet(this, _Router_config, "f"),
|
|
63
|
-
...route,
|
|
64
|
-
method,
|
|
65
|
-
controllers,
|
|
66
|
-
path: (0, exports.formatPath)(`${__classPrivateFieldGet(this, _Router_config, "f")?.path ?? ''}/${route.path ?? ''}`),
|
|
67
|
-
});
|
|
55
|
+
const route = (0, exports.groupRoutes)(__classPrivateFieldGet(this, _Router_config, "f"), [{ ...routeConfig, method, handler }])[0];
|
|
56
|
+
collection.push(route);
|
|
57
|
+
return route;
|
|
68
58
|
};
|
|
69
59
|
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Enum } from '../enums/types';
|
|
2
|
+
import { CustomError } from '../errors';
|
|
3
|
+
import { FastifySchema } from 'fastify';
|
|
4
|
+
import { JSONPrimitives, JSONValue } from '../types';
|
|
5
|
+
import type { Request, Response } from './requests';
|
|
6
|
+
export declare const Methods: {
|
|
7
|
+
readonly get: "get";
|
|
8
|
+
readonly post: "post";
|
|
9
|
+
readonly put: "put";
|
|
10
|
+
readonly patch: "patch";
|
|
11
|
+
readonly delete: "delete";
|
|
12
|
+
};
|
|
13
|
+
export type MethodTypes = Enum<typeof Methods>;
|
|
14
|
+
export declare const StatusCodes: {
|
|
15
|
+
readonly Ok: 200;
|
|
16
|
+
readonly BadRequest: 400;
|
|
17
|
+
readonly NotAuthenticated: 401;
|
|
18
|
+
readonly NotAuthorized: 403;
|
|
19
|
+
readonly NotFound: 404;
|
|
20
|
+
readonly ValidationError: 422;
|
|
21
|
+
readonly TooManyRequests: 429;
|
|
22
|
+
readonly AccessTokenExpired: 461;
|
|
23
|
+
};
|
|
24
|
+
export type SupportedStatusCodes = Enum<typeof StatusCodes>;
|
|
25
|
+
type GoodStatusCodes = 200;
|
|
26
|
+
type ApiErrors = Record<Exclude<SupportedStatusCodes, GoodStatusCodes>, JSONValue<CustomError['serializedErrors']>>;
|
|
27
|
+
type ApiResponse<T, StatusCode extends SupportedStatusCodes> = Record<StatusCode, JSONValue<T>> | Omit<ApiErrors, StatusCode>;
|
|
28
|
+
type Any = object | unknown;
|
|
29
|
+
type Arrayable<T> = T | T[];
|
|
30
|
+
type AllowedResponses = Arrayable<JSONPrimitives | Any>;
|
|
31
|
+
export type Api<Res = AllowedResponses, Key extends string = string, Method extends MethodTypes = MethodTypes, Body extends Any = Any, Params extends Any = Any, Query extends Any = Any, DefaultStatus extends SupportedStatusCodes = SupportedStatusCodes> = {
|
|
32
|
+
key: Key;
|
|
33
|
+
method: Method;
|
|
34
|
+
response: Res;
|
|
35
|
+
body?: Body;
|
|
36
|
+
params?: Params;
|
|
37
|
+
query?: Query;
|
|
38
|
+
defaultStatusCode?: DefaultStatus;
|
|
39
|
+
};
|
|
40
|
+
export type ApiDef<T extends Api = Api> = {
|
|
41
|
+
key: T['key'];
|
|
42
|
+
method: T['method'];
|
|
43
|
+
body: T['body'];
|
|
44
|
+
params: T['params'];
|
|
45
|
+
query: T['query'];
|
|
46
|
+
responses: ApiResponse<T['response'], GetDefaultStatusCode<T['defaultStatusCode']>>;
|
|
47
|
+
__api?: T;
|
|
48
|
+
};
|
|
49
|
+
type Awaitable<T> = Promise<T> | T;
|
|
50
|
+
type Res<T, S extends SupportedStatusCodes> = Awaitable<Response<T, S> | T>;
|
|
51
|
+
type InferApiFromApiDef<T> = T extends ApiDef<infer A> ? A : never;
|
|
52
|
+
type GetDefaultStatusCode<T extends Api['defaultStatusCode']> = T extends SupportedStatusCodes ? T : 200;
|
|
53
|
+
export type RouteHandler<Def extends Api = Api> = (req: Request<Def>) => Res<Def['response'], GetDefaultStatusCode<Def['defaultStatusCode']>>;
|
|
54
|
+
export type ErrorHandler<Def extends Api = Api> = (req: Request<Def>, err: Error) => Res<CustomError['serializedErrors'], GetDefaultStatusCode<Def['defaultStatusCode']>>;
|
|
55
|
+
export type RouteMiddlewareHandler<Def extends Api = Api> = (req: Request<Def>) => Awaitable<void>;
|
|
56
|
+
export type HandlerSetup = (route: Route) => void;
|
|
57
|
+
export type RouteSchema = Omit<FastifySchema, 'tags' | 'security' | 'hide'>;
|
|
58
|
+
export type Route<Def extends ApiDef = ApiDef> = {
|
|
59
|
+
key?: Def['key'];
|
|
60
|
+
path: string;
|
|
61
|
+
method: Def['method'];
|
|
62
|
+
handler: RouteHandler<InferApiFromApiDef<Def>>;
|
|
63
|
+
onSetupHandler?: HandlerSetup;
|
|
64
|
+
middlewares?: ReturnType<typeof makeMiddleware>[];
|
|
65
|
+
onError?: ReturnType<typeof makeErrorMiddleware>;
|
|
66
|
+
schema?: RouteSchema;
|
|
67
|
+
tags?: string[];
|
|
68
|
+
hideSchema?: boolean;
|
|
69
|
+
security?: Record<string, string[]>[];
|
|
70
|
+
__def?: Def;
|
|
71
|
+
};
|
|
72
|
+
export type RouteConfig<T extends ApiDef = ApiDef> = Omit<Route<T>, 'method' | 'handler'>;
|
|
73
|
+
export type GeneralConfig = Omit<RouteConfig, 'schema' | 'key'>;
|
|
74
|
+
export type AddMethodImpls = {
|
|
75
|
+
[Method in MethodTypes]: <T extends ApiDef<Api<AllowedResponses, string, Method>>>(route: RouteConfig<T>) => (handler: RouteHandler<InferApiFromApiDef<T>>) => Route<T>;
|
|
76
|
+
};
|
|
77
|
+
declare class MiddlewareHandler<Cb extends Function> {
|
|
78
|
+
cb: Cb;
|
|
79
|
+
onSetup?: HandlerSetup | undefined;
|
|
80
|
+
private constructor();
|
|
81
|
+
static make<Cb extends Function>(cb: Cb, onSetup?: HandlerSetup): MiddlewareHandler<Cb>;
|
|
82
|
+
}
|
|
83
|
+
export declare const makeMiddleware: <Def extends Api<unknown, string, MethodTypes, unknown, unknown, unknown, SupportedStatusCodes> = Api<unknown, string, MethodTypes, unknown, unknown, unknown, SupportedStatusCodes>>(cb: RouteMiddlewareHandler<Def>, onSetup?: HandlerSetup | undefined) => MiddlewareHandler<RouteMiddlewareHandler<Def>>;
|
|
84
|
+
export declare const makeErrorMiddleware: <Def extends Api<unknown, string, MethodTypes, unknown, unknown, unknown, SupportedStatusCodes> = Api<unknown, string, MethodTypes, unknown, unknown, unknown, SupportedStatusCodes>>(cb: ErrorHandler<Def>, onSetup?: HandlerSetup | undefined) => MiddlewareHandler<ErrorHandler<Def>>;
|
|
85
|
+
export {};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.makeErrorMiddleware = exports.makeMiddleware = exports.StatusCodes = exports.Methods = void 0;
|
|
4
|
+
exports.Methods = {
|
|
5
|
+
get: 'get',
|
|
6
|
+
post: 'post',
|
|
7
|
+
put: 'put',
|
|
8
|
+
patch: 'patch',
|
|
9
|
+
delete: 'delete',
|
|
10
|
+
};
|
|
11
|
+
exports.StatusCodes = {
|
|
12
|
+
Ok: 200,
|
|
13
|
+
BadRequest: 400,
|
|
14
|
+
NotAuthenticated: 401,
|
|
15
|
+
NotAuthorized: 403,
|
|
16
|
+
NotFound: 404,
|
|
17
|
+
ValidationError: 422,
|
|
18
|
+
TooManyRequests: 429,
|
|
19
|
+
AccessTokenExpired: 461,
|
|
20
|
+
};
|
|
21
|
+
class MiddlewareHandler {
|
|
22
|
+
constructor(cb, onSetup) {
|
|
23
|
+
this.cb = cb;
|
|
24
|
+
this.onSetup = onSetup;
|
|
25
|
+
}
|
|
26
|
+
static make(cb, onSetup) {
|
|
27
|
+
return new MiddlewareHandler(cb, onSetup);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const makeMiddleware = (...args) => MiddlewareHandler.make(...args);
|
|
31
|
+
exports.makeMiddleware = makeMiddleware;
|
|
32
|
+
const makeErrorMiddleware = (...args) => MiddlewareHandler.make(...args);
|
|
33
|
+
exports.makeErrorMiddleware = makeErrorMiddleware;
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { ClassPropertiesWrapper } from 'valleyed';
|
|
2
|
-
export declare class BaseEntity<Keys extends
|
|
3
|
-
|
|
4
|
-
ignoreInJSON: string[];
|
|
2
|
+
export declare class BaseEntity<Keys extends object = object, Ignored extends string = string> extends ClassPropertiesWrapper<Keys> {
|
|
3
|
+
__hash: string;
|
|
5
4
|
__type: string;
|
|
6
|
-
|
|
5
|
+
readonly __ignoreInJSON: Ignored[];
|
|
7
6
|
toJSON(includeIgnored?: boolean): Record<string, any>;
|
|
8
|
-
toString(): string;
|
|
7
|
+
toString(includeIgnored?: boolean): string;
|
|
9
8
|
}
|
|
@@ -6,27 +6,35 @@ const utils_1 = require("../utils/utils");
|
|
|
6
6
|
const deleteKeyFromObject = (obj, keys) => {
|
|
7
7
|
if (obj === undefined || obj === null)
|
|
8
8
|
return;
|
|
9
|
-
|
|
9
|
+
const isArray = Array.isArray(obj);
|
|
10
|
+
if (keys.length === 1 && !isArray)
|
|
10
11
|
return delete obj[keys[0]];
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
if (isArray)
|
|
13
|
+
return obj.map((v) => deleteKeyFromObject(v, keys));
|
|
14
|
+
return deleteKeyFromObject(obj[keys[0]], keys.slice(1));
|
|
13
15
|
};
|
|
14
16
|
class BaseEntity extends valleyed_1.ClassPropertiesWrapper {
|
|
15
|
-
constructor(
|
|
16
|
-
super(
|
|
17
|
-
this.
|
|
17
|
+
constructor() {
|
|
18
|
+
super(...arguments);
|
|
19
|
+
this.__hash = utils_1.Random.string();
|
|
18
20
|
this.__type = this.constructor.name;
|
|
19
|
-
this.
|
|
21
|
+
this.__ignoreInJSON = [];
|
|
20
22
|
}
|
|
21
23
|
toJSON(includeIgnored = false) {
|
|
22
|
-
const json =
|
|
24
|
+
const json = {};
|
|
25
|
+
Object.keys(this)
|
|
26
|
+
.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(this)))
|
|
27
|
+
.filter((k) => k !== 'constructor')
|
|
28
|
+
.forEach((key) => {
|
|
29
|
+
const value = this[key];
|
|
30
|
+
json[key] = value?.toJSON?.(includeIgnored) ?? structuredClone(value);
|
|
31
|
+
});
|
|
23
32
|
if (!includeIgnored)
|
|
24
|
-
this.
|
|
25
|
-
delete json.ignoreInJSON;
|
|
33
|
+
this.__ignoreInJSON.concat('__ignoreInJSON').forEach((k) => deleteKeyFromObject(json, k.split('.')));
|
|
26
34
|
return json;
|
|
27
35
|
}
|
|
28
|
-
toString() {
|
|
29
|
-
return JSON.stringify(this.toJSON(
|
|
36
|
+
toString(includeIgnored = true) {
|
|
37
|
+
return JSON.stringify(this.toJSON(includeIgnored), null, 2);
|
|
30
38
|
}
|
|
31
39
|
}
|
|
32
40
|
exports.BaseEntity = BaseEntity;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { BaseEntity } from '../structure';
|
|
2
|
+
export type DeepPartial<T> = {
|
|
3
|
+
[P in keyof T]?: DeepPartial<T[P]>;
|
|
4
|
+
};
|
|
5
|
+
export type DeepOmit<T, K, A = never> = T extends any[] ? DeepOmit<T[number], K, A>[] : T extends (...args: any[]) => any ? never : T extends Array<infer U> ? DeepOmit<U, K, A>[] : {
|
|
6
|
+
[P in keyof T as P extends K | A ? never : P]: DeepOmit<T[P], K extends `${Exclude<P, symbol>}.${infer R}` ? R : never, A>;
|
|
7
|
+
};
|
|
8
|
+
export type DistributiveOmit<T, K extends PropertyKey> = T extends any ? Omit<T, K> : never;
|
|
9
|
+
export type Defined<T> = T extends undefined ? never : T;
|
|
10
|
+
type StopTypes = number | string | boolean | symbol | bigint | Date;
|
|
11
|
+
type ExcludedTypes = (...args: any[]) => any;
|
|
12
|
+
type Dot<T extends string, U extends string> = '' extends U ? T : `${T}.${U}`;
|
|
13
|
+
export type Paths<T, D = never> = T extends StopTypes ? '' : T extends readonly unknown[] ? Paths<T[number]> : {
|
|
14
|
+
[K in keyof T & string]: T[K] extends StopTypes ? K : T[K] extends ExcludedTypes ? D : K | Dot<K, Paths<T[K]>>;
|
|
15
|
+
}[keyof T & string];
|
|
16
|
+
export type JSONPrimitives = string | number | boolean | null;
|
|
17
|
+
export type JSONValue<T> = T extends JSONPrimitives ? T : T extends Array<infer U> ? JSONValue<U>[] : T extends BaseEntity<infer _M, infer I> ? JSONValue<DeepOmit<T, I, '__ignoreInJSON'>> : T extends Function ? never : T extends object ? {
|
|
18
|
+
[K in keyof T & (number | string) as JSONValue<T[K]> extends never ? never : JSONValue<T[K]> extends undefined ? never : K]: JSONValue<T[K]>;
|
|
19
|
+
} : T extends unknown ? unknown : undefined extends T ? JSONValue<Exclude<T, undefined>> | undefined : never;
|
|
20
|
+
export {};
|
|
@@ -154,7 +154,7 @@ export declare const Validation: {
|
|
|
154
154
|
ignored: boolean;
|
|
155
155
|
};
|
|
156
156
|
};
|
|
157
|
-
export declare const validate: <T extends Record<string, Validate.VCore<any>>>(schema: T, value:
|
|
157
|
+
export declare const validate: <T extends Record<string, Validate.VCore<any>>>(schema: T, value: unknown) => { [K in keyof T]: import("valleyed/lib/api/base").ExtractI<T[K]>; };
|
|
158
158
|
export declare const Hash: {
|
|
159
159
|
hash: (password: string) => Promise<string>;
|
|
160
160
|
compare: (plainPassword: string, hashed: string) => Promise<boolean>;
|