oox 0.3.1 → 0.3.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.
@@ -1,6 +1,7 @@
1
1
  import * as http from 'node:http';
2
2
  import * as https from 'node:https';
3
3
  import { httpRequest, parseHTTPBody } from './utils.js';
4
+ import Router from './router.js';
4
5
  import * as oox from '../../index.js';
5
6
  import Module, { ModuleConfig } from '../module.js';
6
7
  export class HTTPConfig extends ModuleConfig {
@@ -26,12 +27,38 @@ export default class HTTPModule extends Module {
26
27
  name = 'http';
27
28
  config = new HTTPConfig;
28
29
  server = null;
30
+ router = new Router();
29
31
  getUrl() {
30
32
  const { host } = oox.config;
31
33
  const { port, path } = this.config;
32
34
  const protocol = this.config.ssl.enabled ? `https:` : `http:`;
33
35
  return `${protocol}//${host}:${port}${path}`;
34
36
  }
37
+ // 注册GET路由
38
+ get(path, ...args) {
39
+ this.router.get(path, ...args);
40
+ return this;
41
+ }
42
+ // 注册POST路由
43
+ post(path, ...args) {
44
+ this.router.post(path, ...args);
45
+ return this;
46
+ }
47
+ // 注册PUT路由
48
+ put(path, ...args) {
49
+ this.router.put(path, ...args);
50
+ return this;
51
+ }
52
+ // 注册DELETE路由
53
+ delete(path, ...args) {
54
+ this.router.delete(path, ...args);
55
+ return this;
56
+ }
57
+ // 注册全局中间件
58
+ use(middleware) {
59
+ this.router.use(middleware);
60
+ return this;
61
+ }
35
62
  setConfig(config) {
36
63
  Object.assign(this.config, config);
37
64
  if (!config.hasOwnProperty('port')) {
@@ -118,7 +145,32 @@ export default class HTTPModule extends Module {
118
145
  async requestHandler(request, response) {
119
146
  if (!this.cors(request, response))
120
147
  return;
121
- const url = new URL(request.url, request.headers.origin || 'http://localhost');
148
+ const url = new URL(request.url, `http://${request.headers.host || 'localhost'}`);
149
+ const method = request.method || 'GET';
150
+ // 尝试匹配路由
151
+ const matched = this.router.match(method, url.pathname);
152
+ if (matched) {
153
+ const req = this.router.createRequestObject(request, url);
154
+ const res = this.router.createResponseObject(response);
155
+ // 解析请求体
156
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
157
+ try {
158
+ req.body = await parseHTTPBody(request);
159
+ }
160
+ catch (error) {
161
+ return this.respond(request, response, {
162
+ success: false,
163
+ error: {
164
+ message: error.message,
165
+ stack: error.stack
166
+ }
167
+ });
168
+ }
169
+ }
170
+ await this.router.handleRoute(matched.route, matched.params, req, res);
171
+ return;
172
+ }
173
+ // 回退到RPC调用
122
174
  if (url.pathname === this.config.path) {
123
175
  await this.call(request, response);
124
176
  }
@@ -0,0 +1,205 @@
1
+ export default class Router {
2
+ routes = new Map();
3
+ globalMiddleware = [];
4
+ // 注册GET路由
5
+ get(path, ...args) {
6
+ const { handler, middleware } = this.parseRouteArgs(args);
7
+ this.addRoute('GET', path, handler, middleware);
8
+ }
9
+ // 注册POST路由
10
+ post(path, ...args) {
11
+ const { handler, middleware } = this.parseRouteArgs(args);
12
+ this.addRoute('POST', path, handler, middleware);
13
+ }
14
+ // 注册PUT路由
15
+ put(path, ...args) {
16
+ const { handler, middleware } = this.parseRouteArgs(args);
17
+ this.addRoute('PUT', path, handler, middleware);
18
+ }
19
+ // 注册DELETE路由
20
+ delete(path, ...args) {
21
+ const { handler, middleware } = this.parseRouteArgs(args);
22
+ this.addRoute('DELETE', path, handler, middleware);
23
+ }
24
+ // 解析路由参数,支持多种传入方式
25
+ parseRouteArgs(args) {
26
+ let handler;
27
+ let middleware = [];
28
+ if (args.length === 0) {
29
+ throw new Error('No handler provided for route');
30
+ }
31
+ // 方式1: [handler] 或 [middlewareArray, handler]
32
+ if (args.length === 1) {
33
+ if (typeof args[0] === 'function') {
34
+ handler = args[0];
35
+ }
36
+ else {
37
+ throw new Error('Invalid route handler');
38
+ }
39
+ }
40
+ // 方式2: [handler, middlewareArray] 或 [middleware1, middleware2, handler] 或 [middlewareArray, handler]
41
+ else {
42
+ // 检查最后一个参数是否是函数(处理器)
43
+ if (typeof args[args.length - 1] === 'function') {
44
+ handler = args[args.length - 1];
45
+ // 前面的所有都是中间件
46
+ const middleArgs = args.slice(0, -1);
47
+ // 展平中间件数组
48
+ for (const arg of middleArgs) {
49
+ if (Array.isArray(arg)) {
50
+ middleware.push(...arg);
51
+ }
52
+ else if (typeof arg === 'function') {
53
+ middleware.push(arg);
54
+ }
55
+ }
56
+ }
57
+ // 检查第一个参数是否是函数
58
+ else if (typeof args[0] === 'function') {
59
+ handler = args[0];
60
+ // 后面的是中间件
61
+ const middleArgs = args.slice(1);
62
+ for (const arg of middleArgs) {
63
+ if (Array.isArray(arg)) {
64
+ middleware.push(...arg);
65
+ }
66
+ else if (typeof arg === 'function') {
67
+ middleware.push(arg);
68
+ }
69
+ }
70
+ }
71
+ else {
72
+ throw new Error('Invalid route arguments');
73
+ }
74
+ }
75
+ return { handler, middleware };
76
+ }
77
+ // 注册全局中间件
78
+ use(middleware) {
79
+ this.globalMiddleware.push(middleware);
80
+ }
81
+ // 注册特定路径的中间件
82
+ usePath(path, middleware) {
83
+ // 实现路径级中间件
84
+ }
85
+ // 添加路由
86
+ addRoute(method, path, handler, middleware = []) {
87
+ if (!this.routes.has(method)) {
88
+ this.routes.set(method, []);
89
+ }
90
+ // 编译路径为正则表达式,支持路径参数
91
+ const { regex, paramNames } = this.compilePath(path);
92
+ this.routes.get(method).push({
93
+ path,
94
+ method,
95
+ handler,
96
+ middleware,
97
+ regex,
98
+ paramNames
99
+ });
100
+ }
101
+ // 编译路径为正则表达式
102
+ compilePath(path) {
103
+ const paramNames = [];
104
+ const regexPattern = path
105
+ .replace(/:([^/]+)/g, (_, paramName) => {
106
+ paramNames.push(paramName);
107
+ return '([^/]+)';
108
+ })
109
+ .replace(/\//g, '\\/')
110
+ .replace(/\*/g, '.*');
111
+ return {
112
+ regex: new RegExp(`^${regexPattern}$`),
113
+ paramNames
114
+ };
115
+ }
116
+ // 匹配路由
117
+ match(method, path) {
118
+ const routes = this.routes.get(method) || [];
119
+ for (const route of routes) {
120
+ const match = path.match(route.regex);
121
+ if (match) {
122
+ const params = {};
123
+ route.paramNames.forEach((paramName, index) => {
124
+ params[paramName] = match[index + 1];
125
+ });
126
+ return { route, params };
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+ // 创建请求对象
132
+ createRequestObject(originalRequest, url) {
133
+ return {
134
+ originalRequest,
135
+ url,
136
+ method: originalRequest.method || 'GET',
137
+ path: url.pathname,
138
+ query: Object.fromEntries(url.searchParams),
139
+ params: {},
140
+ headers: originalRequest.headers,
141
+ body: null
142
+ };
143
+ }
144
+ // 创建响应对象
145
+ createResponseObject(originalResponse) {
146
+ let statusCode = 200;
147
+ return {
148
+ originalResponse,
149
+ status(code) {
150
+ statusCode = code;
151
+ return this;
152
+ },
153
+ json(data) {
154
+ const jsonString = JSON.stringify(data);
155
+ this.originalResponse.statusCode = statusCode;
156
+ this.originalResponse.setHeader('Content-Type', 'application/json');
157
+ this.originalResponse.setHeader('Content-Length', Buffer.byteLength(jsonString));
158
+ this.originalResponse.end(jsonString);
159
+ },
160
+ send(data) {
161
+ const dataString = typeof data === 'string' ? data : JSON.stringify(data);
162
+ this.originalResponse.statusCode = statusCode;
163
+ this.originalResponse.setHeader('Content-Type', 'text/plain');
164
+ this.originalResponse.setHeader('Content-Length', Buffer.byteLength(dataString));
165
+ this.originalResponse.end(dataString);
166
+ },
167
+ end(data) {
168
+ this.originalResponse.statusCode = statusCode;
169
+ this.originalResponse.end(data);
170
+ }
171
+ };
172
+ }
173
+ // 执行中间件
174
+ async executeMiddleware(middleware, req, res) {
175
+ for (const fn of middleware) {
176
+ let nextCalled = false;
177
+ const next = () => { nextCalled = true; };
178
+ const result = fn(req, res, next);
179
+ if (result instanceof Promise) {
180
+ await result;
181
+ }
182
+ if (!nextCalled) {
183
+ return false; // 中间件已结束响应
184
+ }
185
+ }
186
+ return true; // 所有中间件都已执行
187
+ }
188
+ // 处理路由请求
189
+ async handleRoute(route, params, req, res) {
190
+ req.params = params;
191
+ // 执行全局中间件
192
+ const globalMiddlewareContinue = await this.executeMiddleware(this.globalMiddleware, req, res);
193
+ if (!globalMiddlewareContinue)
194
+ return;
195
+ // 执行路由中间件
196
+ const routeMiddlewareContinue = await this.executeMiddleware(route.middleware, req, res);
197
+ if (!routeMiddlewareContinue)
198
+ return;
199
+ // 执行路由处理函数
200
+ const result = route.handler(req, res);
201
+ if (result instanceof Promise) {
202
+ await result;
203
+ }
204
+ }
205
+ }
@@ -29,11 +29,12 @@ export async function parseHTTPBody(request) {
29
29
  // application/json; charset=utf-8
30
30
  if (contentType)
31
31
  contentType = contentType.split(';')[0].trim();
32
- const contentSize = request.headers['content-length'];
33
- if (!contentSize)
32
+ const contentLength = request.headers['content-length'];
33
+ if (!contentLength || contentLength === '0')
34
34
  return null;
35
- const buffer = await stream2buffer(request, +contentSize || 0);
36
- if (contentSize && buffer.length !== +contentSize)
35
+ const contentSize = +contentLength;
36
+ const buffer = await stream2buffer(request, contentSize);
37
+ if (buffer.length !== contentSize)
37
38
  throw new Error('Content-Length Incorrect');
38
39
  switch (contentType) {
39
40
  case 'application/json':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oox",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "OOX Service Engine",
5
5
  "keywords": [
6
6
  "http",
@@ -1,4 +1,5 @@
1
1
  import * as http from 'node:http';
2
+ import Router, { Middleware } from './router.js';
2
3
  import * as oox from '../../index.js';
3
4
  import Module, { ModuleConfig } from '../module.js';
4
5
  export declare class HTTPConfig extends ModuleConfig {
@@ -16,7 +17,13 @@ export default class HTTPModule extends Module {
16
17
  name: string;
17
18
  config: HTTPConfig;
18
19
  server: http.Server;
20
+ router: Router;
19
21
  getUrl(): string;
22
+ get(path: string, ...args: any[]): this;
23
+ post(path: string, ...args: any[]): this;
24
+ put(path: string, ...args: any[]): this;
25
+ delete(path: string, ...args: any[]): this;
26
+ use(middleware: Middleware): this;
20
27
  setConfig(config: HTTPConfig): void;
21
28
  getConfig(): HTTPConfig;
22
29
  /**
@@ -0,0 +1,49 @@
1
+ import * as http from 'node:http';
2
+ export type RouteHandler = (req: Request, res: Response) => Promise<any> | any;
3
+ export type Middleware = (req: Request, res: Response, next: () => void) => Promise<any> | any;
4
+ export interface Route {
5
+ path: string;
6
+ method: string;
7
+ handler: RouteHandler;
8
+ middleware: Middleware[];
9
+ regex: RegExp;
10
+ paramNames: string[];
11
+ }
12
+ export interface Request {
13
+ originalRequest: http.IncomingMessage;
14
+ url: URL;
15
+ method: string;
16
+ path: string;
17
+ query: Record<string, string>;
18
+ params: Record<string, string>;
19
+ headers: Record<string, string>;
20
+ body: any;
21
+ }
22
+ export interface Response {
23
+ originalResponse: http.ServerResponse;
24
+ status(code: number): Response;
25
+ json(data: any): void;
26
+ send(data: any): void;
27
+ end(data?: any): void;
28
+ }
29
+ export default class Router {
30
+ private routes;
31
+ private globalMiddleware;
32
+ get(path: string, ...args: any[]): void;
33
+ post(path: string, ...args: any[]): void;
34
+ put(path: string, ...args: any[]): void;
35
+ delete(path: string, ...args: any[]): void;
36
+ private parseRouteArgs;
37
+ use(middleware: Middleware): void;
38
+ usePath(path: string, middleware: Middleware): void;
39
+ private addRoute;
40
+ private compilePath;
41
+ match(method: string, path: string): {
42
+ route: Route;
43
+ params: Record<string, string>;
44
+ } | null;
45
+ createRequestObject(originalRequest: http.IncomingMessage, url: URL): Request;
46
+ createResponseObject(originalResponse: http.ServerResponse): Response;
47
+ private executeMiddleware;
48
+ handleRoute(route: Route, params: Record<string, string>, req: Request, res: Response): Promise<void>;
49
+ }