diff --git a/playground/socket/package.json b/playground/socket/package.json index 023c3be..6f1995b 100644 --- a/playground/socket/package.json +++ b/playground/socket/package.json @@ -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" } } diff --git a/socket/package.json b/socket/package.json index a6a0d1d..4e2d2b2 100644 --- a/socket/package.json +++ b/socket/package.json @@ -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": [ diff --git a/socket/src/middleware.ts b/socket/src/middleware.ts index baba8f2..855edb3 100644 --- a/socket/src/middleware.ts +++ b/socket/src/middleware.ts @@ -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); } }