Skip to content
This repository has been archived by the owner on Aug 16, 2024. It is now read-only.

Commit

Permalink
Feat: optional global middleware (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
serhiisol authored Jan 9, 2019
1 parent 264be93 commit e3b1cb2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
3 changes: 2 additions & 1 deletion playground/socket/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"url": "https://github.com/serhiiso/node-decorators.git"
},
"scripts": {
"compile": "tsc"
"compile": "tsc",
"install": "rm -rf node_modules/@decorators/socket && cp -r ../../socket node_modules/@decorators && rm -rf node_modules/@decorators/socket/node_modules && rm -rf node_modules/@decorators/socket/src"
}
}
6 changes: 4 additions & 2 deletions socket/package.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
{
"name": "@decorators/socket",
"version": "3.1.0",
"version": "3.2.0",
"description": "node decorators - decorators for socket.io library",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"dependencies": {
"peerDependencies": {
"socket.io": ">=2.1.1",
"@decorators/di": ">=1.0.2"
},
"devDependencies": {
"@types/socket.io": ">=1.4.36",
"@decorators/di": ">=1.0.2",
"socket.io": ">=2.1.1",
"typescript": ">=2.9.2"
},
"keywords": [
Expand Down
28 changes: 25 additions & 3 deletions socket/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,37 @@ export interface Middleware {
*/
export function middlewareHandler(middleware: Type | InjectionToken) {
return function(...args: any[]): any {
let instance: Middleware | ServerMiddleware;
const next: NextFunction = args[args.length - 1];
let instance: Middleware | ServerMiddleware | Type;

try {
instance = Container.get(middleware);
} catch {
try {
instance = new (middleware as Type)();
} catch {
instance = middleware as any;
}
}

// first, assuming that middleware is a class, try to use it,
// otherwise use it as a function
const use = (instance as Middleware | ServerMiddleware).use ?
(instance as Middleware | ServerMiddleware).use : instance as Type;

try {
const result = use.apply(instance, args);

// if result of execution is a promise, add additional listener to catch error
if (result instanceof Promise) {
result.catch(next);
}

return result;
} catch (e) {
instance = new (middleware as Type)();
return next(e);
}

return instance.use.apply(instance, args);
}
}

Expand Down

0 comments on commit e3b1cb2

Please sign in to comment.