feat: 更新cookie模块和添加res和req在app的请求当中

This commit is contained in:
2024-12-11 14:28:46 +08:00
parent c99d03550e
commit dc2f282f4b
8 changed files with 159 additions and 20 deletions

View File

@@ -1,5 +1,5 @@
import { QueryRouter, Route, RouteContext, RouteOpts } from './route.ts';
import { Server, Cors, ServerOpts } from './server/server.ts';
import { Server, Cors, ServerOpts, HandleCtx } from './server/server.ts';
import { WsServer } from './server/ws-server.ts';
import { CustomError } from './result/error.ts';
@@ -14,7 +14,12 @@ type AppOptions<T = {}> = {
io?: boolean;
ioOpts?: { routerHandle?: RouterHandle; routerContext?: RouteContext<T>; path?: string };
};
export class App<T = {}> {
export type AppReqRes = HandleCtx;
/**
* 封装了 Router 和 Server 的 App 模块处理http的请求和响应内置了 Cookie 和 Token 和 res 的处理
*/
export class App<T = {}, U = AppReqRes> {
router: QueryRouter;
server: Server;
io: WsServer;
@@ -55,7 +60,7 @@ export class App<T = {}> {
add = this.addRoute;
Route = Route;
route(opts: RouteOpts): Route;
route(opts: RouteOpts): Route<U>;
route(path: string, key?: string): Route;
route(path: string, opts?: RouteOpts): Route;
route(path: string, key?: string, opts?: RouteOpts): Route;

View File

@@ -69,7 +69,7 @@ export type RouteOpts = {
export type DefineRouteOpts = Omit<RouteOpts, 'idUsePath' | 'verify' | 'verifyKey' | 'nextRoute'>;
const pickValue = ['path', 'key', 'id', 'description', 'type', 'validator', 'middleware'] as const;
export type RouteInfo = Pick<Route, (typeof pickValue)[number]>;
export class Route {
export class Route<U = { [key: string]: any }> {
path?: string;
key?: string;
id?: string;
@@ -207,9 +207,9 @@ export class Route {
return this;
}
define<T extends { [key: string]: any } = RouterContextT>(opts: DefineRouteOpts): this;
define<T extends { [key: string]: any } = RouterContextT>(fn: Run<T>): this;
define<T extends { [key: string]: any } = RouterContextT>(key: string, fn: Run<T>): this;
define<T extends { [key: string]: any } = RouterContextT>(path: string, key: string, fn: Run<T>): this;
define<T extends { [key: string]: any } = RouterContextT>(fn: Run<T & U>): this;
define<T extends { [key: string]: any } = RouterContextT>(key: string, fn: Run<T & U>): this;
define<T extends { [key: string]: any } = RouterContextT>(path: string, key: string, fn: Run<T & U>): this;
define(...args: any[]) {
const [path, key, opts] = args;
// 全覆盖所以opts需要准确不能由idUsePath 需要check的变量
@@ -516,15 +516,19 @@ export class QueryRouter {
});
}
getHandle<T = any>(router: QueryRouter, wrapperFn?: HandleFn<T>, ctx?: RouteContext) {
return async (msg: { path: string; key?: string; [key: string]: any }) => {
const context = { ...ctx };
const res = await router.parse(msg, context);
if (wrapperFn) {
res.data = res.body;
return wrapperFn(res, context);
return async (msg: { path: string; key?: string; [key: string]: any }, handleContext?: RouteContext) => {
try {
const context = { ...ctx, ...handleContext };
const res = await router.parse(msg, context);
if (wrapperFn) {
res.data = res.body;
return wrapperFn(res, context);
}
const { code, body, message } = res;
return { code, data: body, message };
} catch (e) {
return { code: 500, message: e.message };
}
const { code, body, message } = res;
return { code, data: body, message };
};
}
exportRoutes() {

View File

@@ -1,6 +1,7 @@
import http, { IncomingMessage, Server, ServerResponse } from 'http';
import { parseBody } from './parse-body.ts';
import url from 'url';
import { createHandleCtx } from './server.ts';
/**
* get params and body
@@ -20,9 +21,16 @@ export const handleServer = async (req: IncomingMessage, res: ServerResponse) =>
const parsedUrl = url.parse(req.url, true);
// 获取token
let token = req.headers['authorization'] || '';
const handle = createHandleCtx(req, res);
const cookies = handle.req.cookies;
if (!token) {
token = cookies.token;
}
if (token) {
token = token.replace('Bearer ', '');
}
//@ts-ignore
console.log('token', req.cookies, res.cookie);
// 获取查询参数
const param = parsedUrl.query;
let body: Record<any, any>;
@@ -41,6 +49,7 @@ export const handleServer = async (req: IncomingMessage, res: ServerResponse) =>
token,
...param,
...body,
cookies,
};
return data;
};

View File

@@ -2,8 +2,46 @@ import http, { IncomingMessage, ServerResponse } from 'http';
import https from 'https';
import http2 from 'http2';
import { handleServer } from './handle-server.ts';
import * as cookie from 'cookie';
export type Listener = (...args: any[]) => void;
type CookieFn = (name: string, value: string, options?: cookie.SerializeOptions, end?: boolean) => void;
export type HandleCtx = {
req: IncomingMessage & { cookies: Record<string, string> };
res: ServerResponse & {
/**
* cookie 函数, end 参数用于设置是否立即设置到响应头设置了后面的cookie再设置会覆盖前面的
*/
cookie: CookieFn; //
};
};
// 实现函数
export function createHandleCtx(req: IncomingMessage, res: ServerResponse): HandleCtx {
// 用于存储所有的 Set-Cookie 字符串
const cookies: string[] = [];
let handReq = req as HandleCtx['req'];
let handRes = res as HandleCtx['res'];
// 扩展 res.cookie 方法
const cookieFn: CookieFn = (name, value, options = {}, end = true) => {
// 序列化新的 Cookie
const serializedCookie = cookie.serialize(name, value, options);
cookies.push(serializedCookie); // 将新的 Cookie 添加到数组
if (end) {
// 如果设置了 end 参数,则立即设置到响应头
res.setHeader('Set-Cookie', cookies);
}
};
// 解析请求中的现有 Cookie
const parsedCookies = cookie.parse(req.headers.cookie || '');
handReq.cookies = parsedCookies;
handRes.cookie = cookieFn;
// 返回扩展的上下文
return {
req: handReq,
res: handRes,
};
}
export type Cors = {
/**
* @default '*''
@@ -14,7 +52,7 @@ export type ServerOpts = {
/**path default `/api/router` */
path?: string;
/**handle Fn */
handle?: (msg?: { path: string; key?: string; [key: string]: any }) => any;
handle?: (msg?: { path: string; key?: string; [key: string]: any }, ctx?: { req: http.IncomingMessage; res: http.ServerResponse }) => any;
cors?: Cors;
httpType?: 'http' | 'https' | 'http2';
httpsKey?: string;
@@ -131,7 +169,7 @@ export class Server {
return;
}
}
res.writeHead(200); // 设置响应头给予其他任何listen 知道headersSent它已经被响应了
// res.writeHead(200); // 设置响应头给予其他任何listen 知道headersSent它已经被响应了
const url = req.url;
if (!url.startsWith(path)) {
@@ -144,7 +182,10 @@ export class Server {
return;
}
try {
const end = await handle(messages as any);
const end = await handle(messages as any, { req, res });
if (res.writableEnded) {
return;
}
if (typeof end === 'string') {
res.end(end);
} else {