kb-server 0.0.1-beta.21 → 0.0.1-beta.23

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.
@@ -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";
@@ -23,6 +23,7 @@ const CommonErrorsMap = {
23
23
  EmptyParameter: "请求参数不能为空",
24
24
  EmptyAPIRequest: "未指定API的请求",
25
25
  ValidationError: "参数校验失败",
26
+ RouteError: "路由错误",
26
27
  },
27
28
  ResourceNotFound: {
28
29
  APINotFound: "不存在的API",
@@ -1,7 +1,7 @@
1
1
  import express from "express";
2
2
  import { AuthFunction } from "./api-middleware";
3
3
  import { APIs } from "./create-api";
4
- import { SSEHandlers } from "./sse-middleware";
4
+ import { SseHandlers } from "./create-sse";
5
5
  export interface ICreateServerParams {
6
6
  /**
7
7
  * API列表
@@ -11,7 +11,17 @@ export interface ICreateServerParams {
11
11
  * SSE配置
12
12
  */
13
13
  sse?: {
14
- handlers: SSEHandlers;
14
+ /**
15
+ * SSE API列表
16
+ */
17
+ handlers: SseHandlers;
18
+ /**
19
+ * SSE 监听的路由,例如:`/sse/generate`
20
+ *
21
+ * 注意:路由要以 `/` 开头
22
+ *
23
+ * 默认为:`/sse`
24
+ */
15
25
  route?: string;
16
26
  };
17
27
  /**
@@ -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;
@@ -1,25 +1,11 @@
1
1
  import express from "express";
2
- import { ServerContext } from "./create-api";
3
2
  import { AuthFunction } from "./api-middleware";
4
- export type SseExecution<P, R, A> = (
5
- /** 请求入参 */
6
- params: P,
7
- /** 请求上下文 */
8
- ctx: ServerContext<A>,
9
- /**
10
- * 允许执行的操作
11
- */
12
- operations: {
13
- /** 发送消息 */
14
- send: (event: string, message: string) => void;
15
- }) => Promise<R>;
16
- export type AnySseExecution = SseExecution<any, any, any>;
17
- export type SSEHandlers = Record<string, AnySseExecution>;
3
+ import { SseHandlers } from "./create-sse";
18
4
  interface IPackSSEOptions {
19
5
  authFn?: AuthFunction;
20
6
  route?: string;
21
7
  log?: boolean;
22
8
  }
23
- export declare const packSSE: (sseHandlers: SSEHandlers, options?: IPackSSEOptions) => express.RequestHandler;
9
+ export declare const packSSE: (sseHandlers: SseHandlers, options?: IPackSSEOptions) => express.RequestHandler;
24
10
  export declare const createSSEMessage: (event: string, message: string) => string;
25
11
  export {};
@@ -6,14 +6,20 @@ const logger_1 = require("../helper/logger");
6
6
  const create_errors_1 = require("./create-errors");
7
7
  const short_id_1 = require("../helper/short-id");
8
8
  const packSSE = (sseHandlers, options) => {
9
- const sseMap = new Map(Object.entries(sseHandlers).map(([action, execution]) => [
10
- action,
11
- execution,
12
- ]));
13
9
  const { authFn, log = true, route = "/sse" } = options || {};
14
10
  return async (req, res, next) => {
11
+ // 生成SSE API映射
12
+ const sseMap = new Map(Object.entries(sseHandlers).map(([action, execution]) => [
13
+ action,
14
+ execution,
15
+ ]));
16
+ // 检查SSE路由
17
+ const isValidRoute = route.startsWith("/");
18
+ if (!isValidRoute) {
19
+ throw new create_errors_1.CommonErrors.InvalidParameter.RouteError();
20
+ }
15
21
  const { path } = req;
16
- // 路径不是SSE的路径
22
+ // SSE的请求直接放过
17
23
  if (path !== route) {
18
24
  next();
19
25
  return;
@@ -56,17 +62,7 @@ const packSSE = (sseHandlers, options) => {
56
62
  if (typeof execution !== "function") {
57
63
  throw new create_errors_1.CommonErrors.ResourceNotFound.APINotFound();
58
64
  }
59
- /**
60
- * 开始处理SSE请求就要统计
61
- *
62
- * 请求处理完毕的时间
63
- *
64
- * 不要让 API 随意改写 req res 里面的东西
65
- *
66
- * 统一管理请求头
67
- *
68
- */
69
- // 处理SSE
65
+ // 写请求头
70
66
  res.writeHead(200, {
71
67
  "Content-Type": "text/event-stream",
72
68
  "Cache-Control": "no-cache",
@@ -75,7 +71,7 @@ const packSSE = (sseHandlers, options) => {
75
71
  const send = (event, message) => {
76
72
  const response = (0, exports.createSSEMessage)(event, message);
77
73
  res.write(response);
78
- logger_1.logger.log("info", `发送消息:${response}`);
74
+ logger_1.logger.log("info", `发送消息:\n${response}`);
79
75
  };
80
76
  await execution(params, ctx, { send });
81
77
  // 完成响应
@@ -106,7 +102,7 @@ const packSSE = (sseHandlers, options) => {
106
102
  }));
107
103
  // 完成响应
108
104
  took = Date.now() - start;
109
- logger_1.logger.log("info", `响应:${response}`);
105
+ logger_1.logger.log("info", `发送消息:\n${response}`);
110
106
  logger_1.logger.log("info", `耗时:${took} ms - RequestId: ${requestId}`);
111
107
  res.write(response);
112
108
  return res.end();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kb-server",
3
- "version": "0.0.1-beta.21",
3
+ "version": "0.0.1-beta.23",
4
4
  "description": "A fast server for Node.JS,made by express.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {