Skip to content

Commit

Permalink
Feature/0.4.1 (#11)
Browse files Browse the repository at this point in the history
* chore: 强制锁定 @types/node 包的版本

* refactor: 重构 IMiddlewareAbility 接口中的 next 类型

* feat: 将中间件抛出的错误进行处理

* feat: 检查中间件是否被多次调用,防止多余的 next 调用

* chore: 更换包管理工具为 yarn

* refactor: 简化导出语句

* refactor: 使用 throwXXX 函数抛出错误
  • Loading branch information
divasatanica committed May 6, 2022
1 parent 9ab1f87 commit 9d97e16
Show file tree
Hide file tree
Showing 17 changed files with 94 additions and 57 deletions.
5 changes: 3 additions & 2 deletions demo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ const server = new Server({
assetsRoot: Config.publicDir
});

routerMap.get('/', async (ctx, next) => {
ctx.body = '';
routerMap.get('/test-multi', async (ctx, next) => {
ctx.body = 'hi~';
next && await next(ctx);
next && await next(ctx);
});

Expand Down
3 changes: 2 additions & 1 deletion lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
"ignoreChanges": ["ignored-file", "*.md"],
"message": "chore(release): publish",
"registry": "https://registry.npmjs.org"
}
},
"npmClient": "yarn"
}
5 changes: 4 additions & 1 deletion packages/auf-typing/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,8 @@
"rimraf": "^3.0.2",
"typescript": "^4.6.2"
},
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b"
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b",
"resolutions": {
"@types/node": "15.6.2"
}
}
8 changes: 7 additions & 1 deletion packages/auf-typing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ export interface IServerOptions {
errorHandler?: (e: Error) => void;
}

export type ContextExtendInfoType = {
visMap: WeakSet<IMiddleWare>;
handled: boolean;
[key: string]: any;
}

export interface IContext {
req: http.IncomingMessage;
res: http.ServerResponse;
serverOptions: IServerOptions;
body: string | Readable | Record<string, any>;
extendInfo: Record<string, any>;
extendInfo: ContextExtendInfoType;
get reqBody(): Record<string, any>;
get query(): Record<string, string>;
get params(): Record<string, string>;
Expand Down
10 changes: 1 addition & 9 deletions packages/auf/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
export {
Server,
ClusterServer,
Router,
RouterMapFactory,
IClusterServerOptions,
CommonError,
isCommonError
} from '@vergiss/auf-core';
export * from '@vergiss/auf-core';

export * as Middlewares from '@vergiss/auf-middlewares';
export { IContext, IMiddleWare, IServerOptions } from '@vergiss/auf-typing';
5 changes: 4 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,8 @@
"dependencies": {
"@vergiss/auf-helpers": "^0.3.0"
},
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b"
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b",
"resolutions": {
"@types/node": "15.6.2"
}
}
15 changes: 3 additions & 12 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
import { ClusterServer, Server, IClusterServerOptions } from './server';
import { Router, RouterMapFactory } from './router';
export { ClusterServer, Server, IClusterServerOptions } from './server';
export { Router, RouterMapFactory } from './router';

export { CommonError, isCommonError } from '@vergiss/auf-helpers';
export {
Server,
ClusterServer,
Router,
RouterMapFactory,

// declarations
IClusterServerOptions,
}
export { CommonError, isCommonError, throwCommonError } from '@vergiss/auf-helpers';
8 changes: 4 additions & 4 deletions packages/core/src/router/prefix-tree/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

import { CommonError } from '@vergiss/auf-helpers';
import { throwCommonError } from '@vergiss/auf-helpers';
import {
NTreeNode,
RouterRegExpLeafNode,
Expand Down Expand Up @@ -78,7 +78,7 @@ class NTree<T> implements IRouterTree<T> {
const matchedRegExpNodes = regExpNodes.filter(node => node.exp.test(url));

if (matchedRegExpNodes.length === 0) {
throw new CommonError({
throwCommonError({
message: 'Route not defined',
statusCode: 404,
statusMessage: 'Not Found'
Expand Down Expand Up @@ -143,11 +143,11 @@ class NTree<T> implements IRouterTree<T> {
const leafNode = p.quickMap.get(LEAF_SIGN);

if (leafNode == null) {
throw new CommonError({
throwCommonError({
message: 'Handler not defined',
statusCode: 500,
statusMessage: 'Handler Not Found'
});
})
}

res = (leafNode as RouterTreeLeafNode<T>).value;
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ class BaseServer implements IBaseServer {
const { port } = this.options;
http.createServer(async (_, res) => {
const ctx = new Context(_, res, this.options);
if (handleContext) {
await handleContext(ctx);
}
try {
if (handleContext) {
await handleContext(ctx);
}
if (ctx.body == null) {
res.end('');
return;
Expand Down
9 changes: 6 additions & 3 deletions packages/core/src/server/context.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import * as http from 'http';
import { IContext, IServerOptions } from '@vergiss/auf-typing';
import { IContext, IServerOptions, ContextExtendInfoType } from '@vergiss/auf-typing';

class Context implements IContext {
public res: http.ServerResponse;
public req: http.IncomingMessage;
public serverOptions: IServerOptions;
public extendInfo: any;
public extendInfo: ContextExtendInfoType;
private _body: any;
constructor (req: http.IncomingMessage, res: http.ServerResponse, serverOptions: IServerOptions) {
this.res = res;
this.req = req;
this.serverOptions = serverOptions;
this._body = {} as any;
this.extendInfo = {} as any;
this.extendInfo = {
visMap: new WeakSet(),
handled: false
};
}

get body() {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ export interface IClusterServerOptions extends IServerOptions {
}

export interface IMiddlewareAbility {
next(ctx: IContext): Promise<unknown>;
next(ctx: IContext): void;
applyMiddleware(middlewares: IMiddleWare[]): void
}
41 changes: 32 additions & 9 deletions packages/core/src/server/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,54 @@ import { compose } from '@vergiss/auf-helpers';
import { IContext, IMiddleWare } from '@vergiss/auf-typing';
import { IMiddlewareAbility } from './interface';

/**
* Check if a middleware is called multiple times. It has side effect.
* @param fn The middleware function
* @param ctx Context object
*/
function checkIfMultipleVisited (fn: IMiddleWare, ctx: IContext) {
if (ctx.extendInfo.visMap.has(fn)) {
throw new Error('The "next" method can\'t be called multiple times.');
}
ctx.extendInfo.visMap.add(fn);
}

/**
* Returns a resolved promise as the middlewares chain's tail.
* @param ctx Context object
*/
function wrapResolvedPromise (ctx: IContext) {
checkIfMultipleVisited(wrapResolvedPromise, ctx);
return Promise.resolve();
}

class Middlewares {
public middlewares: Function[];
constructor (middlewares: Function[]) {
private middlewares: Array<IMiddleWare>;
private wrappedMiddlewares: Array<(fn?: IMiddleWare) => void>;
constructor (middlewares: IMiddleWare[]) {
this.middlewares = middlewares
}

applyMiddlewares(): (ctx: IContext) => Promise<unknown> {
this.middlewares = this.middlewares.map(fn => {
return function (next = (() => Promise.resolve())) {
getMiddlewareChain(): (ctx: IContext) => void {
this.wrappedMiddlewares = this.middlewares.map(fn => {
return function (next = wrapResolvedPromise) {
return async function (ctx: IContext) {
checkIfMultipleVisited(fn, ctx);
await fn(ctx, next);
}
}
})
const [lastActionGenerator, ...restActionGenerators] = this.middlewares.reverse();
});
const [lastActionGenerator, ...restActionGenerators] = this.wrappedMiddlewares.reverse();

return compose(restActionGenerators)(lastActionGenerator());
}
}

export class MiddlewaresAbility implements IMiddlewareAbility {
next: (ctx: IContext) => Promise<unknown>;
next: (ctx: IContext) => void;
private middleware: Middlewares;
applyMiddleware(middlewares: IMiddleWare[]): void {
this.middleware = new Middlewares(middlewares);
this.next = this.middleware.applyMiddlewares();
this.next = this.middleware.getMiddlewareChain();
}
}
5 changes: 4 additions & 1 deletion packages/helpers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,8 @@
"ts-node": "^10.7.0",
"typescript": "^4.3.2"
},
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b"
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b",
"resolutions": {
"@types/node": "15.6.2"
}
}
7 changes: 6 additions & 1 deletion packages/helpers/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,15 @@ class CommonError extends Error {
}
}

function throwCommonError(options: ICommonErrorOptions): never {
throw new CommonError(options);
}

function isCommonError (value: any): value is CommonError {
return value.type === commonErrorSymbol;
}
export {
CommonError,
isCommonError
isCommonError,
throwCommonError
}
12 changes: 6 additions & 6 deletions packages/helpers/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { compose, composePromise } from './functional';
export { checkMimeTypes } from './mime-type';
export { uuid } from './tools';
export { getMD5 } from './md5';
export { LRUCache } from './lru-cache';
export { CommonError, isCommonError } from './error';
export * from './functional';
export * from './mime-type';
export * from './tools';
export * from './md5';
export * from './lru-cache';
export * from './error';

5 changes: 4 additions & 1 deletion packages/middlewares/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,8 @@
"@vergiss/auf-helpers": "^0.3.0",
"@vergiss/auf-template-engine": "^0.4.0"
},
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b"
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b",
"resolutions": {
"@types/node": "15.6.2"
}
}
5 changes: 4 additions & 1 deletion packages/template-engine/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@
"ts-node": "^10.7.0",
"typescript": "^4.3.2"
},
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b"
"gitHead": "3f74b38e9dc2a875da3de1a32d4c045acb975d7b",
"resolutions": {
"@types/node": "15.6.2"
}
}

0 comments on commit 9d97e16

Please sign in to comment.