kb-server 0.0.1-beta.3 → 0.0.1-beta.30
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 +16 -1
- package/dist/common/api-middleware.d.ts +2 -1
- package/dist/common/api-middleware.js +14 -6
- package/dist/common/call-service.d.ts +1 -0
- package/dist/common/call-service.js +27 -0
- package/dist/common/create-api.d.ts +15 -6
- package/dist/common/create-api.js +26 -5
- package/dist/common/create-errors.d.ts +3 -0
- package/dist/common/create-errors.js +1 -0
- package/dist/common/create-server.d.ts +56 -0
- package/dist/common/create-server.js +8 -2
- package/dist/common/create-sse.d.ts +23 -0
- package/dist/common/create-sse.js +31 -0
- package/dist/common/sse-middleware.d.ts +11 -0
- package/dist/common/sse-middleware.js +130 -0
- package/dist/helper/logger.d.ts +6 -0
- package/dist/helper/logger.js +17 -0
- package/dist/helper/short-id.d.ts +1 -0
- package/dist/helper/short-id.js +7 -0
- package/dist/helper/sleep.d.ts +1 -0
- package/dist/helper/sleep.js +5 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +5 -1
- package/package.json +7 -3
package/README.md
CHANGED
|
@@ -2,4 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
快速创建一个 Node 服务
|
|
4
4
|
|
|
5
|
-
快速创建API、标准错误码、Server、支持统一鉴权函数(API
|
|
5
|
+
快速创建 API、标准错误码、Server、支持统一鉴权函数(API 级别)、自定义中间件、日志、支持SSE
|
|
6
|
+
|
|
7
|
+
```javascript
|
|
8
|
+
import { createServer } from "kb-server";
|
|
9
|
+
import * as apis from "./apis";
|
|
10
|
+
|
|
11
|
+
// 写法一
|
|
12
|
+
const server = createServer({ apis });
|
|
13
|
+
server.listen(3000);
|
|
14
|
+
|
|
15
|
+
// 写法二
|
|
16
|
+
(async () => {
|
|
17
|
+
// 其他的异步操作,例如:初始化数据库
|
|
18
|
+
return createServer({ apis });
|
|
19
|
+
})().then((app) => app.listen(3000));
|
|
20
|
+
```
|
|
@@ -23,9 +23,10 @@ export interface APIErrorResponse {
|
|
|
23
23
|
RequestId: string;
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
-
export type AuthFunction = (action: string, req: express.Request) => Promise<Record<string, any> |
|
|
26
|
+
export type AuthFunction = (action: string, req: express.Request) => Promise<Record<string, any> | boolean> | boolean | Record<string, any>;
|
|
27
27
|
interface IPackAPIOptions {
|
|
28
28
|
authFn?: AuthFunction;
|
|
29
|
+
log?: boolean;
|
|
29
30
|
}
|
|
30
31
|
/**
|
|
31
32
|
* API包装函数
|
|
@@ -3,13 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.packAPI = void 0;
|
|
4
4
|
const create_errors_1 = require("./create-errors");
|
|
5
5
|
const uuid_1 = require("uuid");
|
|
6
|
+
const logger_1 = require("../helper/logger");
|
|
6
7
|
/**
|
|
7
8
|
* API包装函数
|
|
8
9
|
* @param apis API列表
|
|
9
10
|
* @returns
|
|
10
11
|
*/
|
|
11
12
|
const packAPI = (apis, options) => {
|
|
12
|
-
const { authFn } = options || {};
|
|
13
|
+
const { authFn, log = true } = options || {};
|
|
13
14
|
return async (req, res) => {
|
|
14
15
|
// 生成API映射
|
|
15
16
|
const apiMap = new Map(Object.entries(apis).map(([action, execution]) => [action, execution]));
|
|
@@ -25,6 +26,9 @@ const packAPI = (apis, options) => {
|
|
|
25
26
|
try {
|
|
26
27
|
// API 解析
|
|
27
28
|
const { Action, ...params } = req.body || {};
|
|
29
|
+
if (log) {
|
|
30
|
+
logger_1.logger.log("info", `请求入参:${JSON.stringify(req.body)} - RequestId: ${requestId}`);
|
|
31
|
+
}
|
|
28
32
|
// 接口未定义
|
|
29
33
|
if (!Action) {
|
|
30
34
|
throw new create_errors_1.CommonErrors.InvalidParameter.EmptyAPIRequest();
|
|
@@ -38,8 +42,10 @@ const packAPI = (apis, options) => {
|
|
|
38
42
|
if (!authResult) {
|
|
39
43
|
throw new create_errors_1.CommonErrors.FailOperation.NoPermission();
|
|
40
44
|
}
|
|
41
|
-
|
|
42
|
-
|
|
45
|
+
if (typeof authResult !== "boolean") {
|
|
46
|
+
// 把权限信息写入上下文
|
|
47
|
+
ctx.AuthInfo = authResult || {};
|
|
48
|
+
}
|
|
43
49
|
}
|
|
44
50
|
// API 处理
|
|
45
51
|
const execution = apiMap.get(Action);
|
|
@@ -57,11 +63,12 @@ const packAPI = (apis, options) => {
|
|
|
57
63
|
};
|
|
58
64
|
// 完成响应
|
|
59
65
|
took = Date.now() - start;
|
|
60
|
-
|
|
66
|
+
logger_1.logger.log("info", `响应:${JSON.stringify(response)}`);
|
|
67
|
+
logger_1.logger.log("info", `耗时:${took} ms - RequestId: ${requestId}`);
|
|
61
68
|
return res.send(response);
|
|
62
69
|
}
|
|
63
70
|
catch (rawError) {
|
|
64
|
-
|
|
71
|
+
logger_1.logger.log("error", rawError);
|
|
65
72
|
// 未知错误
|
|
66
73
|
let error = new create_errors_1.CommonErrors.InternalError.UnknownError();
|
|
67
74
|
// 可控错误
|
|
@@ -83,7 +90,8 @@ const packAPI = (apis, options) => {
|
|
|
83
90
|
};
|
|
84
91
|
// 完成响应
|
|
85
92
|
took = Date.now() - start;
|
|
86
|
-
|
|
93
|
+
logger_1.logger.log("info", `响应:${JSON.stringify(response)}`);
|
|
94
|
+
logger_1.logger.log("info", `耗时:${took} ms - RequestId: ${requestId}`);
|
|
87
95
|
return res.send(response);
|
|
88
96
|
}
|
|
89
97
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const callService: <P = Record<string, any>, R = any>(endpoint: string, body: P) => Promise<R>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.callService = void 0;
|
|
7
|
+
const node_fetch_1 = __importDefault(require("node-fetch"));
|
|
8
|
+
const create_errors_1 = require("./create-errors");
|
|
9
|
+
const callService = async (endpoint, body) => {
|
|
10
|
+
const response = await (0, node_fetch_1.default)(endpoint, {
|
|
11
|
+
headers: {
|
|
12
|
+
"Content-Type": "application/json",
|
|
13
|
+
},
|
|
14
|
+
method: "POST",
|
|
15
|
+
body: JSON.stringify(body),
|
|
16
|
+
});
|
|
17
|
+
const result = await response.json();
|
|
18
|
+
if (result?.Response?.Error) {
|
|
19
|
+
const errMsg = result.Response.Error?.Message;
|
|
20
|
+
if (errMsg) {
|
|
21
|
+
throw new create_errors_1.CommonErrors.InternalError.ServiceError(errMsg);
|
|
22
|
+
}
|
|
23
|
+
throw new create_errors_1.CommonErrors.InternalError.ServiceError();
|
|
24
|
+
}
|
|
25
|
+
return result?.Response?.Data;
|
|
26
|
+
};
|
|
27
|
+
exports.callService = callService;
|
|
@@ -1,15 +1,24 @@
|
|
|
1
|
+
import { ValidationError } from "class-validator";
|
|
1
2
|
import { Class } from "utility-types";
|
|
2
|
-
export interface ServerContext {
|
|
3
|
+
export interface ServerContext<A = any> {
|
|
3
4
|
/** 被调用方的 RequestId */
|
|
4
5
|
RequestId: string;
|
|
5
6
|
/** 权限信息 */
|
|
6
|
-
AuthInfo?:
|
|
7
|
+
AuthInfo?: A;
|
|
7
8
|
}
|
|
8
9
|
export type API<P, R> = (param: P) => Promise<R>;
|
|
9
|
-
export type APIExecution<P, R> = (
|
|
10
|
-
|
|
10
|
+
export type APIExecution<P, R, A> = (
|
|
11
|
+
/** 请求入参 */
|
|
12
|
+
params: P,
|
|
13
|
+
/** 请求上下文 */
|
|
14
|
+
ctx: ServerContext<A>) => Promise<R>;
|
|
15
|
+
export type AnyAPIExecution = APIExecution<any, any, any>;
|
|
11
16
|
export type APIs = Record<string, AnyAPIExecution>;
|
|
12
|
-
export declare function createAPI<P, R>(ParamsClass: Class<P>, execution: APIExecution<P, R>): API<P, R>;
|
|
17
|
+
export declare function createAPI<P, R, A>(ParamsClass: Class<P>, execution: APIExecution<P, R, A>): API<P, R>;
|
|
13
18
|
type StubParam<T> = T extends (params: infer P) => any ? P : never;
|
|
14
|
-
export declare function implementAPI<
|
|
19
|
+
export declare function implementAPI<F extends (params: any) => any, A = Record<string, any>>(_actionStub: F, ParamsClass: Class<StubParam<F>>, execution: APIExecution<StubParam<F>, ReturnType<F>, A>): API<StubParam<F>, ReturnType<F>>;
|
|
20
|
+
/**
|
|
21
|
+
* 解析错误信息
|
|
22
|
+
*/
|
|
23
|
+
export declare function getMessage(message: ValidationError, propertyPath?: string): string[];
|
|
15
24
|
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.implementAPI = exports.createAPI = void 0;
|
|
3
|
+
exports.getMessage = exports.implementAPI = exports.createAPI = void 0;
|
|
4
4
|
const class_transformer_1 = require("class-transformer");
|
|
5
5
|
const class_validator_1 = require("class-validator");
|
|
6
6
|
const create_errors_1 = require("./create-errors");
|
|
@@ -15,10 +15,8 @@ function createAPI(ParamsClass, execution) {
|
|
|
15
15
|
: (0, class_transformer_1.plainToClass)(ParamsClass, params);
|
|
16
16
|
const errors = await (0, class_validator_1.validate)(paramsToCheck || {});
|
|
17
17
|
if (errors?.length) {
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
});
|
|
21
|
-
throw new create_errors_1.CommonErrors.InvalidParameter.ValidationError(messages.join(" "));
|
|
18
|
+
const errorMessages = errors.flatMap((error) => getMessage(error));
|
|
19
|
+
throw new create_errors_1.CommonErrors.InvalidParameter.ValidationError(errorMessages.join("\n"));
|
|
22
20
|
}
|
|
23
21
|
// 执行函数
|
|
24
22
|
return await execution(params, ctx);
|
|
@@ -30,3 +28,26 @@ function implementAPI(_actionStub, ParamsClass, execution) {
|
|
|
30
28
|
return createAPI(ParamsClass, execution);
|
|
31
29
|
}
|
|
32
30
|
exports.implementAPI = implementAPI;
|
|
31
|
+
/**
|
|
32
|
+
* 解析错误信息
|
|
33
|
+
*/
|
|
34
|
+
function getMessage(message, propertyPath = "") {
|
|
35
|
+
const messages = [];
|
|
36
|
+
// 构建当前属性的完整路径
|
|
37
|
+
const currentPropertyPath = propertyPath
|
|
38
|
+
? `${propertyPath}.${message.property}`
|
|
39
|
+
: message.property;
|
|
40
|
+
if (message.constraints) {
|
|
41
|
+
// 将所有约束错误合并为一个字符串
|
|
42
|
+
const constraintErrors = Object.values(message.constraints).join(", ");
|
|
43
|
+
messages.push(`${currentPropertyPath}: ${constraintErrors}`);
|
|
44
|
+
}
|
|
45
|
+
if (message.children && message.children.length > 0) {
|
|
46
|
+
// 递归处理子错误,并传递更新后的属性路径
|
|
47
|
+
for (const [_index, child] of message.children.entries()) {
|
|
48
|
+
messages.push(...getMessage(child, currentPropertyPath));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return messages;
|
|
52
|
+
}
|
|
53
|
+
exports.getMessage = getMessage;
|
|
@@ -21,6 +21,7 @@ declare const CommonErrorsMap: {
|
|
|
21
21
|
readonly EmptyParameter: "请求参数不能为空";
|
|
22
22
|
readonly EmptyAPIRequest: "未指定API的请求";
|
|
23
23
|
readonly ValidationError: "参数校验失败";
|
|
24
|
+
readonly RouteError: "路由错误";
|
|
24
25
|
};
|
|
25
26
|
readonly ResourceNotFound: {
|
|
26
27
|
readonly APINotFound: "不存在的API";
|
|
@@ -77,6 +78,7 @@ declare function createErrorsClasses<T extends MessageMap = MessageMap>(messageM
|
|
|
77
78
|
readonly EmptyParameter: "请求参数不能为空";
|
|
78
79
|
readonly EmptyAPIRequest: "未指定API的请求";
|
|
79
80
|
readonly ValidationError: "参数校验失败";
|
|
81
|
+
readonly RouteError: "路由错误";
|
|
80
82
|
};
|
|
81
83
|
readonly ResourceNotFound: {
|
|
82
84
|
readonly APINotFound: "不存在的API";
|
|
@@ -102,6 +104,7 @@ export declare const CommonErrors: ErrorClasses<MergeMessageMap<{
|
|
|
102
104
|
readonly EmptyParameter: "请求参数不能为空";
|
|
103
105
|
readonly EmptyAPIRequest: "未指定API的请求";
|
|
104
106
|
readonly ValidationError: "参数校验失败";
|
|
107
|
+
readonly RouteError: "路由错误";
|
|
105
108
|
};
|
|
106
109
|
readonly ResourceNotFound: {
|
|
107
110
|
readonly APINotFound: "不存在的API";
|
|
@@ -1,8 +1,64 @@
|
|
|
1
|
+
import express from "express";
|
|
1
2
|
import { AuthFunction } from "./api-middleware";
|
|
2
3
|
import { APIs } from "./create-api";
|
|
4
|
+
import { SseHandlers } from "./create-sse";
|
|
3
5
|
export interface ICreateServerParams {
|
|
6
|
+
/**
|
|
7
|
+
* API列表
|
|
8
|
+
*/
|
|
4
9
|
apis: APIs;
|
|
10
|
+
/**
|
|
11
|
+
* SSE配置
|
|
12
|
+
*/
|
|
13
|
+
sse?: {
|
|
14
|
+
/**
|
|
15
|
+
* SSE API列表
|
|
16
|
+
*/
|
|
17
|
+
handlers: SseHandlers;
|
|
18
|
+
/**
|
|
19
|
+
* SSE 监听的路由,例如:`/sse/generate`
|
|
20
|
+
*
|
|
21
|
+
* 注意:路由要以 `/` 开头
|
|
22
|
+
*
|
|
23
|
+
* 默认为:`/sse`
|
|
24
|
+
*/
|
|
25
|
+
route?: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* 鉴权函数
|
|
29
|
+
*
|
|
30
|
+
* 可以通过返回布尔值来定义权限,也可以直接返回数据对象,数据对象会被传递到上下文 ctx 中(AuthInfo)
|
|
31
|
+
*/
|
|
5
32
|
authFn?: AuthFunction;
|
|
33
|
+
/**
|
|
34
|
+
* 默认请求日志,true开启,false关闭
|
|
35
|
+
*/
|
|
36
|
+
log?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* 自定义中间件列表
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
*
|
|
42
|
+
* ```
|
|
43
|
+
* import cors from "cors"; // 引入cors中间件
|
|
44
|
+
*
|
|
45
|
+
* ...其他代码...
|
|
46
|
+
*
|
|
47
|
+
* const server = createServer(
|
|
48
|
+
* {
|
|
49
|
+
* apis: myAPIs,
|
|
50
|
+
* authFn: myAuthFunction,
|
|
51
|
+
* log: true,
|
|
52
|
+
* middlewares: [cors()], // 传入cors中间件
|
|
53
|
+
* },
|
|
54
|
+
* {
|
|
55
|
+
* limit: "5mb",
|
|
56
|
+
* }
|
|
57
|
+
*);
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
*/
|
|
61
|
+
middlewares?: express.RequestHandler[];
|
|
6
62
|
}
|
|
7
63
|
export interface ICreateServerOptions {
|
|
8
64
|
limit?: string | number | undefined;
|
|
@@ -26,18 +26,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
26
26
|
exports.createServer = void 0;
|
|
27
27
|
const express_1 = __importStar(require("express"));
|
|
28
28
|
const api_middleware_1 = require("./api-middleware");
|
|
29
|
+
const sse_middleware_1 = require("./sse-middleware");
|
|
29
30
|
/**
|
|
30
31
|
* 创建 Server
|
|
31
32
|
*/
|
|
32
33
|
function createServer(params, options) {
|
|
33
|
-
const { apis, authFn } = params || {};
|
|
34
|
+
const { apis, sse, authFn, log, middlewares = [] } = params || {};
|
|
34
35
|
const { limit = "10mb" } = options || {};
|
|
36
|
+
const { handlers, route } = sse || {};
|
|
35
37
|
const app = (0, express_1.default)();
|
|
36
38
|
// POST 参数获取
|
|
37
39
|
app.use((0, express_1.urlencoded)({ extended: true, limit }));
|
|
38
40
|
app.use((0, express_1.json)({ limit }));
|
|
41
|
+
// 使用自定义中间件
|
|
42
|
+
middlewares.forEach((middleware) => app.use(middleware));
|
|
43
|
+
// 注入SSE
|
|
44
|
+
handlers && app.use((0, sse_middleware_1.packSSE)(handlers, { route }));
|
|
39
45
|
// 注入API
|
|
40
|
-
app.use((0, api_middleware_1.packAPI)(apis, { authFn }));
|
|
46
|
+
app.use((0, api_middleware_1.packAPI)(apis, { authFn, log }));
|
|
41
47
|
return app;
|
|
42
48
|
}
|
|
43
49
|
exports.createServer = createServer;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Class } from "utility-types";
|
|
2
|
+
import { ServerContext } from "./create-api";
|
|
3
|
+
export type API<P, R> = (param: P) => Promise<R>;
|
|
4
|
+
export type SseExecution<P, R, A> = (
|
|
5
|
+
/** 请求入参 */
|
|
6
|
+
params: P,
|
|
7
|
+
/** 请求上下文 */
|
|
8
|
+
ctx: ServerContext<A>,
|
|
9
|
+
/**
|
|
10
|
+
* 操作函数
|
|
11
|
+
*/
|
|
12
|
+
operations: {
|
|
13
|
+
/**
|
|
14
|
+
* 向客户端推送消息
|
|
15
|
+
*/
|
|
16
|
+
send: (event: string, message: string) => void;
|
|
17
|
+
}) => Promise<R>;
|
|
18
|
+
export type AnySseExecution = SseExecution<any, any, any>;
|
|
19
|
+
export type SseHandlers = Record<string, AnySseExecution>;
|
|
20
|
+
export declare function createSseAPI<P, R, A>(ParamsClass: Class<P>, execution: SseExecution<P, R, A>): API<P, R>;
|
|
21
|
+
type StubParam<T> = T extends (params: infer P) => any ? P : never;
|
|
22
|
+
export declare function implementSseAPI<F extends (params: any) => any, A = Record<string, any>>(_actionStub: F, ParamsClass: Class<StubParam<F>>, execution: SseExecution<StubParam<F>, ReturnType<F>, A>): API<StubParam<F>, ReturnType<F>>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.implementSseAPI = exports.createSseAPI = void 0;
|
|
4
|
+
const class_transformer_1 = require("class-transformer");
|
|
5
|
+
const class_validator_1 = require("class-validator");
|
|
6
|
+
const create_errors_1 = require("./create-errors");
|
|
7
|
+
const create_api_1 = require("./create-api");
|
|
8
|
+
function createSseAPI(ParamsClass, execution) {
|
|
9
|
+
const runtime = async (params, ctx, operations) => {
|
|
10
|
+
if (!params) {
|
|
11
|
+
throw new create_errors_1.CommonErrors.InvalidParameter.EmptyParameter();
|
|
12
|
+
}
|
|
13
|
+
// 校验参数
|
|
14
|
+
const paramsToCheck = params instanceof ParamsClass
|
|
15
|
+
? params
|
|
16
|
+
: (0, class_transformer_1.plainToClass)(ParamsClass, params);
|
|
17
|
+
const errors = await (0, class_validator_1.validate)(paramsToCheck || {});
|
|
18
|
+
if (errors?.length) {
|
|
19
|
+
const errorMessages = errors.flatMap((error) => (0, create_api_1.getMessage)(error));
|
|
20
|
+
throw new create_errors_1.CommonErrors.InvalidParameter.ValidationError(errorMessages.join("\n"));
|
|
21
|
+
}
|
|
22
|
+
// 执行函数
|
|
23
|
+
return await execution(params, ctx, operations);
|
|
24
|
+
};
|
|
25
|
+
return runtime;
|
|
26
|
+
}
|
|
27
|
+
exports.createSseAPI = createSseAPI;
|
|
28
|
+
function implementSseAPI(_actionStub, ParamsClass, execution) {
|
|
29
|
+
return createSseAPI(ParamsClass, execution);
|
|
30
|
+
}
|
|
31
|
+
exports.implementSseAPI = implementSseAPI;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import { AuthFunction } from "./api-middleware";
|
|
3
|
+
import { SseHandlers } from "./create-sse";
|
|
4
|
+
interface IPackSSEOptions {
|
|
5
|
+
authFn?: AuthFunction;
|
|
6
|
+
route?: string;
|
|
7
|
+
log?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare const packSSE: (sseHandlers: SseHandlers, options?: IPackSSEOptions) => express.RequestHandler;
|
|
10
|
+
export declare const createSSEMessage: (event: string, message: string) => string;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createSSEMessage = exports.packSSE = void 0;
|
|
4
|
+
const uuid_1 = require("uuid");
|
|
5
|
+
const logger_1 = require("../helper/logger");
|
|
6
|
+
const create_errors_1 = require("./create-errors");
|
|
7
|
+
const short_id_1 = require("../helper/short-id");
|
|
8
|
+
const sleep_1 = require("../helper/sleep");
|
|
9
|
+
const packSSE = (sseHandlers, options) => {
|
|
10
|
+
const { authFn, log = true, route = "/sse" } = options || {};
|
|
11
|
+
return async (req, res, next) => {
|
|
12
|
+
// 生成SSE API映射
|
|
13
|
+
const sseMap = new Map(Object.entries(sseHandlers).map(([action, execution]) => [
|
|
14
|
+
action,
|
|
15
|
+
execution,
|
|
16
|
+
]));
|
|
17
|
+
// 检查SSE路由
|
|
18
|
+
const isValidRoute = route.startsWith("/");
|
|
19
|
+
if (!isValidRoute) {
|
|
20
|
+
throw new create_errors_1.CommonErrors.InvalidParameter.RouteError();
|
|
21
|
+
}
|
|
22
|
+
const { path } = req;
|
|
23
|
+
// 非SSE的请求直接放过
|
|
24
|
+
if (path !== route) {
|
|
25
|
+
next();
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
// 请求开始时间
|
|
29
|
+
const start = Date.now();
|
|
30
|
+
let took = 0;
|
|
31
|
+
// 生成请求ID
|
|
32
|
+
const requestId = (0, uuid_1.v4)();
|
|
33
|
+
// 上下文
|
|
34
|
+
const ctx = {
|
|
35
|
+
RequestId: requestId,
|
|
36
|
+
};
|
|
37
|
+
try {
|
|
38
|
+
// API 解析
|
|
39
|
+
const { Action, ...params } = req.body || {};
|
|
40
|
+
if (log) {
|
|
41
|
+
logger_1.logger.log("info", `请求入参:${JSON.stringify(req.body)} - RequestId: ${requestId}`);
|
|
42
|
+
}
|
|
43
|
+
// 接口未定义
|
|
44
|
+
if (!Action) {
|
|
45
|
+
throw new create_errors_1.CommonErrors.InvalidParameter.EmptyAPIRequest();
|
|
46
|
+
}
|
|
47
|
+
// 处理鉴权函数
|
|
48
|
+
if (authFn !== null && authFn !== undefined) {
|
|
49
|
+
if (typeof authFn !== "function") {
|
|
50
|
+
throw new create_errors_1.CommonErrors.ResourceNotFound.AuthFunctionNotFound();
|
|
51
|
+
}
|
|
52
|
+
const authResult = await authFn(Action, req);
|
|
53
|
+
if (!authResult) {
|
|
54
|
+
throw new create_errors_1.CommonErrors.FailOperation.NoPermission();
|
|
55
|
+
}
|
|
56
|
+
if (typeof authResult !== "boolean") {
|
|
57
|
+
// 把权限信息写入上下文
|
|
58
|
+
ctx.AuthInfo = authResult || {};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// API 处理
|
|
62
|
+
const execution = sseMap.get(Action);
|
|
63
|
+
if (typeof execution !== "function") {
|
|
64
|
+
throw new create_errors_1.CommonErrors.ResourceNotFound.APINotFound();
|
|
65
|
+
}
|
|
66
|
+
// 写请求头
|
|
67
|
+
res.writeHead(200, {
|
|
68
|
+
"Content-Type": "text/event-stream",
|
|
69
|
+
"Cache-Control": "no-cache",
|
|
70
|
+
Connection: "keep-alive",
|
|
71
|
+
});
|
|
72
|
+
const send = (event, message) => {
|
|
73
|
+
const response = (0, exports.createSSEMessage)(event, message);
|
|
74
|
+
res.write(response);
|
|
75
|
+
logger_1.logger.log("info", `发送消息:\n${response}`);
|
|
76
|
+
};
|
|
77
|
+
await execution(params, ctx, { send });
|
|
78
|
+
// 完成响应
|
|
79
|
+
took = Date.now() - start;
|
|
80
|
+
logger_1.logger.log("info", `耗时:${took} ms - RequestId: ${requestId}`);
|
|
81
|
+
// 延迟1ms关闭连接
|
|
82
|
+
await (0, sleep_1.sleep)(1);
|
|
83
|
+
return res.end();
|
|
84
|
+
}
|
|
85
|
+
catch (rawError) {
|
|
86
|
+
logger_1.logger.log("error", rawError);
|
|
87
|
+
if (!res.headersSent) {
|
|
88
|
+
// 写请求头
|
|
89
|
+
res.writeHead(200, {
|
|
90
|
+
"Content-Type": "text/event-stream",
|
|
91
|
+
"Cache-Control": "no-cache",
|
|
92
|
+
Connection: "keep-alive",
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
// 未知错误
|
|
96
|
+
let error = new create_errors_1.CommonErrors.InternalError.UnknownError();
|
|
97
|
+
// 可控错误
|
|
98
|
+
if (rawError instanceof create_errors_1.BaseError) {
|
|
99
|
+
error = rawError;
|
|
100
|
+
}
|
|
101
|
+
// DB错误
|
|
102
|
+
if (rawError?.sql) {
|
|
103
|
+
error = new create_errors_1.CommonErrors.InternalError.DatabaseError();
|
|
104
|
+
}
|
|
105
|
+
const response = (0, exports.createSSEMessage)("error", JSON.stringify({
|
|
106
|
+
Response: {
|
|
107
|
+
Error: { Code: error.code, Message: error.message },
|
|
108
|
+
RequestId: requestId,
|
|
109
|
+
},
|
|
110
|
+
}));
|
|
111
|
+
// 完成响应
|
|
112
|
+
took = Date.now() - start;
|
|
113
|
+
logger_1.logger.log("info", `发送消息:\n${response}`);
|
|
114
|
+
logger_1.logger.log("info", `耗时:${took} ms - RequestId: ${requestId}`);
|
|
115
|
+
res.write(response);
|
|
116
|
+
// 延迟1ms关闭连接
|
|
117
|
+
await (0, sleep_1.sleep)(1);
|
|
118
|
+
return res.end();
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
exports.packSSE = packSSE;
|
|
123
|
+
const createSSEMessage = (event, message) => {
|
|
124
|
+
const id = (0, short_id_1.shortId)();
|
|
125
|
+
const idStr = `id: ${id}\n`;
|
|
126
|
+
const eventStr = `event: ${event}\n`;
|
|
127
|
+
const dataStr = `data: ${message}\n\n`;
|
|
128
|
+
return idStr + eventStr + dataStr;
|
|
129
|
+
};
|
|
130
|
+
exports.createSSEMessage = createSSEMessage;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.logger = void 0;
|
|
7
|
+
const moment_1 = __importDefault(require("moment"));
|
|
8
|
+
exports.logger = { log };
|
|
9
|
+
function log(level, message) {
|
|
10
|
+
const logTime = (0, moment_1.default)().format(`YYYY-MM-DD HH:mm:ss`);
|
|
11
|
+
if (typeof message === "string") {
|
|
12
|
+
console.log(`[${level}] - [${logTime}] - ${message}`);
|
|
13
|
+
}
|
|
14
|
+
else {
|
|
15
|
+
console.log(`[${level}] - [${logTime}] - `, message);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const shortId: () => string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.shortId = void 0;
|
|
4
|
+
const nanoid_1 = require("nanoid");
|
|
5
|
+
const nanoid = (0, nanoid_1.customAlphabet)("123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", 10);
|
|
6
|
+
const shortId = () => nanoid();
|
|
7
|
+
exports.shortId = shortId;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const sleep: (ms: number) => Promise<unknown>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { createServer } from "./common/create-server";
|
|
2
2
|
export { createErrors } from "./common/create-errors";
|
|
3
|
-
export { implementAPI } from "./common/create-api";
|
|
3
|
+
export { implementAPI, ServerContext } from "./common/create-api";
|
|
4
|
+
export { implementSseAPI } from "./common/create-sse";
|
|
5
|
+
export { callService } from "./common/call-service";
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.implementAPI = exports.createErrors = exports.createServer = void 0;
|
|
3
|
+
exports.callService = exports.implementSseAPI = exports.implementAPI = exports.createErrors = exports.createServer = void 0;
|
|
4
4
|
var create_server_1 = require("./common/create-server");
|
|
5
5
|
Object.defineProperty(exports, "createServer", { enumerable: true, get: function () { return create_server_1.createServer; } });
|
|
6
6
|
var create_errors_1 = require("./common/create-errors");
|
|
7
7
|
Object.defineProperty(exports, "createErrors", { enumerable: true, get: function () { return create_errors_1.createErrors; } });
|
|
8
8
|
var create_api_1 = require("./common/create-api");
|
|
9
9
|
Object.defineProperty(exports, "implementAPI", { enumerable: true, get: function () { return create_api_1.implementAPI; } });
|
|
10
|
+
var create_sse_1 = require("./common/create-sse");
|
|
11
|
+
Object.defineProperty(exports, "implementSseAPI", { enumerable: true, get: function () { return create_sse_1.implementSseAPI; } });
|
|
12
|
+
var call_service_1 = require("./common/call-service");
|
|
13
|
+
Object.defineProperty(exports, "callService", { enumerable: true, get: function () { return call_service_1.callService; } });
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kb-server",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.30",
|
|
4
4
|
"description": "A fast server for Node.JS,made by express.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"scripts": {
|
|
7
|
-
"build": "rm -rf ./dist
|
|
7
|
+
"build": "rm -rf ./dist && tsc",
|
|
8
8
|
"test": "echo \"Error: no test specified\" && exit 1"
|
|
9
9
|
},
|
|
10
10
|
"keywords": [
|
|
@@ -23,10 +23,14 @@
|
|
|
23
23
|
"class-validator": "^0.14.1",
|
|
24
24
|
"express": "^4.21.1",
|
|
25
25
|
"is-plain-object": "^5.0.0",
|
|
26
|
+
"moment": "^2.30.1",
|
|
27
|
+
"nanoid": "^3.3.9",
|
|
28
|
+
"node-fetch": "^2.7.0",
|
|
26
29
|
"utility-types": "^3.11.0",
|
|
27
30
|
"uuid": "^11.0.3"
|
|
28
31
|
},
|
|
29
32
|
"devDependencies": {
|
|
30
|
-
"@types/express": "^4.17.21"
|
|
33
|
+
"@types/express": "^4.17.21",
|
|
34
|
+
"@types/node-fetch": "^2.6.12"
|
|
31
35
|
}
|
|
32
36
|
}
|