Skip to content

Commit

Permalink
✨ Add possibility to add custom routes
Browse files Browse the repository at this point in the history
  • Loading branch information
MalteSehmer committed Jun 21, 2023
1 parent 72a5efc commit ae60eb3
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
45 changes: 44 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import {
IntegrationEntityBridgeRequest,
} from "./models";
import { CustomRouter } from "./models/custom-router.model";
import { CustomRoute } from "./models/custom-routes.model";
import { getContactCache } from "./util/get-contact-cache";
import { errorLogger, infoLogger } from "./util";

const PORT: number = Number(process.env.PORT) || 8080;

Expand All @@ -32,7 +34,8 @@ let cache: ContactCache | null = null;

export function start(
adapter: Adapter,
customRouters: CustomRouter[] = []
customRouters: CustomRouter[] = [],
customRoutes: CustomRoute[] = []
): Server {
cache = getContactCache();

Expand Down Expand Up @@ -93,6 +96,46 @@ export function start(

customRouters.forEach(({ path, router }) => app.use(path, router));

customRoutes.forEach(({ requestType, path, handler: customHandler }) => {
infoLogger("start", `CustomRoute ${path} added.`, undefined);

const handler = (req: any, res: any, next: any) => {
try {
infoLogger(path, "START", undefined);

customHandler(req, res, next);

infoLogger(path, "END", undefined);
} catch (error) {
errorLogger(
path,
"Error while executing custom route",
undefined,
error ?? undefined
);
next(error);
}
};

switch (requestType) {
case "get":
app.get(path, handler);
break;
case "post":
app.post(path, handler);
break;
case "put":
app.put(path, handler);
break;
case "delete":
app.delete(path, handler);
break;

default:
throw `CustomRoute requestType ${requestType} not implemented!`;
}
});

return app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
}

Expand Down
7 changes: 7 additions & 0 deletions src/models/custom-routes.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { RequestHandler } from "express";

export type CustomRoute = {
requestType: "get" | "post" | "put" | "delete";
path: string;
handler: RequestHandler;
};

0 comments on commit ae60eb3

Please sign in to comment.