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

Add metadata #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.2.0 - Unreleased

- Add `getMetadata()` from `RoutexInversifyServer` for built and resolved metadata
- Added `callsites` to track where the decorators are used

## 0.1.1 - 2020-04-12

- Bind `InjectableMiddleware`
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@routex/inversify",
"version": "0.1.1",
"version": "0.2.0",
"description": "Inversify decorators for Routex",
"keywords": [
"routex",
Expand Down Expand Up @@ -65,6 +65,9 @@
".ts": "ts-jest"
}
},
"dependencies": {
"callsites": "^3.1.0"
},
"devDependencies": {
"@types/jest": "^25.2.1",
"@types/node": "^13.11.1",
Expand Down
2 changes: 1 addition & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ export const TYPE = {

export const METADATA_KEY = {
controller: "_controller",
controllerMethod: "_controller-method",
controllerHandler: "_controller-handler",
};
20 changes: 13 additions & 7 deletions src/decorators.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as routex from "routex";
import * as interfaces from "./interfaces";
import { METADATA_KEY } from "./constants";
import * as callsites from "callsites";

export function Controller(
path?: string,
Expand All @@ -9,8 +10,9 @@ export function Controller(
return function (target: any) {
const metadata: interfaces.IControllerMetadata = {
path,
middlewares,
middlewares: middlewares ?? [],
target,
callsite: callsites()[4],
};
Reflect.defineMetadata(METADATA_KEY.controller, metadata, target);
};
Expand All @@ -23,28 +25,32 @@ export function Method(
options?: routex.IRouteOptions
): interfaces.IHandlerDecorator {
return function (target: routex.Handler, key: string) {
const metadata: interfaces.IControllerMethodMetadata = {
const metadata: interfaces.IControllerHandlerMetadata = {
path,
options,
middlewares,
middlewares: middlewares ?? [],
method,
target,
key,
callsite: callsites()[4],
};

let metadataList: interfaces.IControllerMethodMetadata[] = [];
let metadataList: interfaces.IControllerHandlerMetadata[] = [];

if (
!Reflect.hasOwnMetadata(METADATA_KEY.controllerMethod, target.constructor)
!Reflect.hasOwnMetadata(
METADATA_KEY.controllerHandler,
target.constructor
)
) {
Reflect.defineMetadata(
METADATA_KEY.controllerMethod,
METADATA_KEY.controllerHandler,
metadataList,
target.constructor
);
} else {
metadataList = Reflect.getOwnMetadata(
METADATA_KEY.controllerMethod,
METADATA_KEY.controllerHandler,
target.constructor
);
}
Expand Down
24 changes: 21 additions & 3 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as routex from "routex";
import { interfaces as inversifyInterfaces } from "inversify";
import { CallSite } from "callsites";

// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface InjectableMiddleware {
Expand All @@ -12,19 +13,36 @@ export type IMiddleware =

export interface IControllerMetadata {
path?: string;
middlewares?: IMiddleware[];
middlewares: IMiddleware[];
target: any;
callsite: CallSite;
}

export interface IControllerMethodMetadata {
export interface IControllerHandlerMetadata {
path: string;
options?: routex.IRouteOptions;
middlewares?: IMiddleware[];
middlewares: IMiddleware[];
target: any;
method: routex.Methods;
key: string;
callsite: CallSite;
}

export interface IHandlerDecorator {
(target: any, key: string, value: any): void;
}

export interface IResolvedControllerHandlerMetadata
extends IControllerHandlerMetadata {
resolvedMiddlewares: routex.Middleware[];
}

export interface IResolvedControllerMetadata extends IControllerMetadata {
resolvedHandlers: IResolvedControllerHandlerMetadata[];
resolvedMiddlewares: routex.Middleware[];
resolvedRouter: routex.Router;
}

export interface IRoutexServerMetadata {
controllers: IResolvedControllerMetadata[];
}
106 changes: 70 additions & 36 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export class RoutexInversifyServer {
private readonly app: routex.Routex;
private readonly defaultRoot: IRoutexInversifyOptions["defaultRoot"];

private metadata?: interfaces.IRoutexServerMetadata;

constructor(
container: inversify.interfaces.Container,
options?: IRoutexInversifyOptions
Expand All @@ -26,61 +28,86 @@ export class RoutexInversifyServer {
}

public build(): routex.Routex {
this.registerControllers();
if (!this.metadata) {
this.metadata = this.registerControllers();
}

return this.app;
}

private registerControllers() {
private registerControllers(): interfaces.IRoutexServerMetadata {
const router = this.defaultRoot
? this.app.child(this.defaultRoot)
: this.app;

const controllers = this.container.getAll<object>(TYPE.Controller);

controllers.forEach((controller) => {
const controllerMetadata: interfaces.IControllerMetadata = Reflect.getOwnMetadata(
METADATA_KEY.controller,
controller.constructor
);

const methodMetadatas: interfaces.IControllerMethodMetadata[] = Reflect.getOwnMetadata(
METADATA_KEY.controllerMethod,
controller.constructor
);
const resolvedControllers = controllers
.map((controller): interfaces.IResolvedControllerMetadata | undefined => {
// Get metadata from @Controller decorator
const controllerMetadata: interfaces.IControllerMetadata = Reflect.getOwnMetadata(
METADATA_KEY.controller,
controller.constructor
);

if (controllerMetadata && methodMetadatas) {
const controllerMiddleware = this.resolveMiddlewares(
controllerMetadata.middlewares
// Get all @Method decorators from controller
const handlerMetadatas: interfaces.IControllerHandlerMetadata[] = Reflect.getOwnMetadata(
METADATA_KEY.controllerHandler,
controller.constructor
);

const controllerRouter = router.child(controllerMetadata.path ?? "/");
if (controllerMetadata && handlerMetadatas) {
const controllerMiddlewares = this.resolveMiddlewares(
controllerMetadata.middlewares
);

controllerRouter.middleware(controllerMiddleware);
const controllerRouter = router.child(controllerMetadata.path ?? "/");

controllerRouter.middleware(controllerMiddlewares);

const resolvedHandlers = handlerMetadatas.map(
(
handlerMetadata
): interfaces.IResolvedControllerHandlerMetadata => {
const handler = (controller as any)[handlerMetadata.key];

const handlerMiddlewares = this.resolveMiddlewares(
handlerMetadata.middlewares
);

// Add route to controller router
controllerRouter.route(
handlerMetadata.method,
handlerMetadata.path,
[...handlerMiddlewares, handler.bind(controller)],
handlerMetadata.options
);

return {
...handlerMetadata,
resolvedMiddlewares: handlerMiddlewares,
};
}
);

methodMetadatas.forEach((methodMetadata) => {
const handler = (controller as any)[methodMetadata.key];
return {
...controllerMetadata,
resolvedHandlers,
resolvedMiddlewares: controllerMiddlewares,
resolvedRouter: controllerRouter,
};
}

const routeMiddleware = this.resolveMiddlewares(
methodMetadata.middlewares
);
return undefined;
})
.filter(Boolean);

controllerRouter.route(
methodMetadata.method,
methodMetadata.path,
[...routeMiddleware, handler.bind(controller)],
methodMetadata.options
);
});
}
});
return {
controllers: resolvedControllers as interfaces.IResolvedControllerMetadata[],
};
}

private resolveMiddlewares(middlewares?: interfaces.IMiddleware[]) {
if (!middlewares) {
return [];
}

private resolveMiddlewares(middlewares: interfaces.IMiddleware[]) {
return middlewares.map((middleware) => {
try {
const resolvedMiddleware = this.container.get<
Expand All @@ -97,4 +124,11 @@ export class RoutexInversifyServer {
}
});
}

public getMetadata() {
this.build();

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.metadata!;
}
}
2 changes: 1 addition & 1 deletion test/controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ function middleware2(ctx: ICtx) {
ctx.data.name += "doe";
}

@Controller(undefined, [middleware1, "globalMiddleware1"])
@Controller("/middleware", [middleware1, "globalMiddleware1"])
@injectable()
export class MiddlewareTestController {
@Get("/name", [middleware2, "globalMiddleware2"])
Expand Down
50 changes: 49 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ it("Supports middlewares", () => {
const server = new RoutexInversifyServer(container);

return request(server.build().handler)
.get("/name")
.get("/middleware/name")
.expect(`{"name":"JOHN H DOE"}`)
.expect("Content-Type", /json/)
.expect(200);
Expand Down Expand Up @@ -180,3 +180,51 @@ it("Supports this", () => {
.expect("Content-Type", /json/)
.expect(200);
});

it("Injects metadata", () => {
const container = new Container();
container
.bind(TYPE.Controller)
.to(MiddlewareTestController)
.whenTargetNamed("MiddlewareTestController");

container.bind("globalMiddleware1").toConstantValue((ctx: ICtx) => {
ctx.data.name += " h ";
});

container.bind("globalMiddleware2").toConstantValue((ctx: ICtx) => {
ctx.data.name = ctx.data.name.toUpperCase();
});

const server = new RoutexInversifyServer(container);

const metadata = server.getMetadata();

expect(metadata.controllers.length).toBe(1);

const controller = metadata.controllers[0];

expect(controller.path).toBe("/middleware");

expect(controller.middlewares.length).toBe(2);
expect(controller.middlewares[1]).toBe("globalMiddleware1");
expect(controller.resolvedMiddlewares.length).toBe(2);

expect(controller.resolvedHandlers.length).toBe(1);

const handler = controller.resolvedHandlers[0];

expect(handler.path).toBe("/name");
expect(handler.method).toBe("get");
expect(handler.options).toBe(undefined);

expect(handler.middlewares.length).toBe(2);
expect(handler.middlewares[1]).toBe("globalMiddleware2");
expect(handler.resolvedMiddlewares.length).toBe(2);

return request(server.build().handler)
.get("/middleware/name")
.expect(`{"name":"JOHN H DOE"}`)
.expect("Content-Type", /json/)
.expect(200);
});
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1154,7 +1154,7 @@ cache-base@^1.0.1:
union-value "^1.0.0"
unset-value "^1.0.0"

callsites@^3.0.0:
callsites@^3.0.0, callsites@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73"
integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==
Expand Down