@sjoblomtobias/relay 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,20 @@
1
- MIT License
1
+ Pirate License
2
2
 
3
- Copyright (c) 2025 Tobias Sjöblom
3
+ Copyright (c) 2026 Tobias Sjöblom
4
4
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
5
+ Avast! Permission be hereby granted, free o’ charge, to any scallywag obtainin’ a copy
6
+ o’ this software and its associated treasure maps (the “Software”), to plunder and deal
7
+ with it without restriction, includin’ without limit the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and sell
9
+ copies o’ the Software, and to allow other swashbucklers to do the same,
10
+ subject to the followin’ code of the sea:
11
11
 
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
12
+ The above copyright notice and this permission notice shall be hoisted on all
13
+ copies or substantial portions o’ the Software.
14
14
 
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ THE SOFTWARE BE PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDIN’ BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISIN’ FROM,
20
+ OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS THEREIN.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # relay
2
+
3
+ A lightweight TypeScript framework for building structured Express applications with decorator-based routing.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @sjoblomtobias/relay
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### 1. Create a route
14
+
15
+ Extend the `Route` class and decorate it with `@Public` or `@Private`. Override any of the built-in HTTP method handlers you need.
16
+
17
+ ```ts
18
+ // src/routes/users.ts
19
+ import { Public, Route } from "@sjoblomtobias/relay";
20
+ import type { Request, Response, NextFunction } from "express";
21
+
22
+ @Public("/users")
23
+ export default class UsersRoute extends Route {
24
+ protected get(req: Request, res: Response, next: NextFunction): void {
25
+ res.json([{ id: 1, name: "Alice" }]);
26
+ }
27
+
28
+ protected getById(req: Request, res: Response, next: NextFunction): void {
29
+ res.json({ id: req.params.id });
30
+ }
31
+
32
+ protected post(req: Request, res: Response, next: NextFunction): void {
33
+ res.status(201).json(req.body);
34
+ }
35
+
36
+ protected patch(req: Request, res: Response, next: NextFunction): void {
37
+ res.json({ id: req.params.id, ...req.body });
38
+ }
39
+
40
+ protected delete(req: Request, res: Response, next: NextFunction): void {
41
+ res.status(204).send();
42
+ }
43
+ }
44
+ ```
45
+
46
+ ### 2. Decorators
47
+
48
+ | Decorator | Description |
49
+ |-----------|-------------|
50
+ | `@Public(path)` | Registers the route at `path` without authentication |
51
+ | `@Private(path)` | Registers the route at `path`, applies `authMiddleware` if provided |
52
+ | `@Location(path, isPrivate?)` | Base decorator used by `@Public` and `@Private` |
53
+
54
+ ### 3. Register routes and start the server
55
+
56
+ Import each route class explicitly and pass it to `registerRoutes`. Routes are never loaded implicitly from the filesystem, so the set of registered routes is always visible directly in your code.
57
+
58
+ ```ts
59
+ // src/index.ts
60
+ import { Server } from "@sjoblomtobias/relay";
61
+ import UsersRoute from "./routes/users.js";
62
+
63
+ const server = new Server(3000);
64
+
65
+ server.registerRoutes(UsersRoute);
66
+
67
+ await server.start(undefined, () => {
68
+ console.log("Ready!");
69
+ });
70
+ ```
71
+
72
+ ### 4. Authentication middleware
73
+
74
+ Pass an Express `RequestHandler` as the second argument to `Server`. It will be applied to all routes decorated with `@Private`. A route decorated with `@Private` throws when it's registered without an `authMiddleware` in place — set it before calling `registerRoutes`.
75
+
76
+ ```ts
77
+ import { Server } from "@sjoblomtobias/relay";
78
+
79
+ const authMiddleware = (req, res, next) => {
80
+ if (!req.headers.authorization) return res.status(401).send("Unauthorized");
81
+ next();
82
+ };
83
+
84
+ const server = new Server(3000, authMiddleware);
85
+ ```
86
+
87
+ You can also set it separately, as long as it happens before `registerRoutes`:
88
+
89
+ ```ts
90
+ server.setAuthMiddleware(authMiddleware);
91
+ server.registerRoutes(UsersRoute);
92
+ ```
93
+
94
+ ## API
95
+
96
+ ### `Server`
97
+
98
+ | Method | Description |
99
+ |--------|-------------|
100
+ | `new Server(port, authMiddleware?)` | Creates a new server instance |
101
+ | `registerRoutes(...routeClasses)` | Registers one or more route classes. Throws if a `@Private` route is registered before `authMiddleware` is set |
102
+ | `start(before?, after?)` | Starts the server. Awaits optional `before` callback, binds the port, then awaits optional `after` callback |
103
+ | `use(...handlers)` | Adds Express middleware |
104
+ | `getApp()` | Returns the underlying Express app |
105
+ | `setAuthMiddleware(middleware)` | Sets or replaces the authentication middleware. Must be called before `registerRoutes` for any `@Private` route |
106
+
107
+ ### `Route`
108
+
109
+ Abstract base class. Override any of the following optional methods:
110
+
111
+ | Method | HTTP method | Path |
112
+ |--------|-------------|------|
113
+ | `get` | GET | `/location` |
114
+ | `getById` | GET | `/location/:id` |
115
+ | `post` | POST | `/location` |
116
+ | `patch` | PATCH | `/location/:id` |
117
+ | `delete` | DELETE | `/location/:id` |
118
+
119
+ Override `getEndpoints()` to fully customize the endpoint configuration.
120
+
121
+ ## Security
122
+
123
+ `Server` ships with a couple of safe defaults: the `X-Powered-By` header is disabled, and unhandled route errors are caught and returned as a generic `500` (the error message and stack trace are only included in the response when `NODE_ENV=development`).
124
+
125
+ Beyond that, relay is intentionally minimal and does not add any hardening middleware for you. Depending on what your app is exposed to, consider adding:
126
+
127
+ - [`helmet`](https://www.npmjs.com/package/helmet) for standard security headers (CSP, HSTS, etc.)
128
+ - A rate limiter such as [`express-rate-limit`](https://www.npmjs.com/package/express-rate-limit) to slow down brute-force and abuse
129
+ - Body size limits on `express.json()` / `express.urlencoded()` to avoid oversized request payloads
130
+
131
+ These can be registered like any other Express middleware via `server.use(...)`:
132
+
133
+ ```ts
134
+ import helmet from "helmet";
135
+ import rateLimit from "express-rate-limit";
136
+ import express from "express";
137
+
138
+ server.use(helmet(), rateLimit({ windowMs: 60_000, limit: 100 }), express.json({ limit: "100kb" }));
139
+ ```
140
+
141
+ Also keep in mind:
142
+
143
+ - `authMiddleware` must be set (via the `Server` constructor or `setAuthMiddleware`) **before** calling `registerRoutes` — registering a `@Private` route without it throws rather than silently serving the route unprotected.
144
+ - Route classes are only ever registered explicitly via `registerRoutes`; nothing is loaded implicitly from the filesystem, so the set of exposed routes is always visible in your own code.
145
+
146
+ ## License
147
+
148
+ Pirate
package/dist/index.d.ts CHANGED
@@ -1,7 +1,2 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Entry point for the application.
5
- */
6
1
  export * from "./route.js";
7
2
  export * from "./server.js";
package/dist/index.js CHANGED
@@ -1,7 +1,2 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Entry point for the application.
5
- */
6
1
  export * from "./route.js";
7
2
  export * from "./server.js";
package/dist/route.d.ts CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Base class for defining routes in an Express application.
5
- */
6
1
  import { Router } from "express";
7
2
  import type { Request, Response, NextFunction } from "express";
8
3
  /**
package/dist/route.js CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Base class for defining routes in an Express application.
5
- */
6
1
  import { Router } from "express";
7
2
  /**
8
3
  * Decorator to set the base path and authentication requirement for a route class.
@@ -49,15 +44,12 @@ export class Route {
49
44
  * Initializes the routes based on the implemented methods in the subclass.
50
45
  */
51
46
  initializeRoutes() {
47
+ if (this.isPrivate && !this.authMiddleware) {
48
+ throw new Error(`Route "${this.location}" is marked private but no authMiddleware was provided. Refusing to register it unprotected.`);
49
+ }
52
50
  this.getEndpoints().forEach(({ path, handler, routerMethod }) => {
53
51
  if (typeof handler === "function") {
54
- let handlers;
55
- if (this.isPrivate && this.authMiddleware) {
56
- handlers = [this.authMiddleware, handler.bind(this)];
57
- }
58
- else {
59
- handlers = [handler.bind(this)];
60
- }
52
+ const handlers = this.isPrivate && this.authMiddleware ? [this.authMiddleware, handler.bind(this)] : [handler.bind(this)];
61
53
  const fullPath = path ? `${this.location}${path}` : `${this.location}`;
62
54
  routerMethod(fullPath, ...handlers);
63
55
  }
package/dist/server.d.ts CHANGED
@@ -1,27 +1,27 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Class representing an Express server that dynamically loads routes from a specified directory.
5
- */
6
1
  import express from "express";
2
+ import type { Route } from "./route.js";
7
3
  import type { RequestHandler } from "express";
4
+ export type RouteConstructor = new (authMiddleware?: RequestHandler) => Route;
8
5
  export declare class Server {
9
6
  private port;
10
- private routesDirectory;
11
7
  private app;
12
8
  private authMiddleware?;
13
9
  /**
14
10
  * Creates an instance of the Server class.
15
11
  * @param port The port number on which the server will listen.
16
- * @param routesDirectory The directory where route files are located.
17
12
  * @param authMiddleware Optional authentication middleware to be used for private routes.
18
13
  */
19
- constructor(port: number, routesDirectory: string, authMiddleware?: RequestHandler);
14
+ constructor(port: number, authMiddleware?: RequestHandler);
20
15
  /**
21
- * Loads all routes from the specified directory.
22
- * @returns Promise that resolves when all routes are loaded.
16
+ * Default error handler. Returns a generic 500 response, only including
17
+ * the error message and stack trace when NODE_ENV is "development".
23
18
  */
24
- loadRoutes(): Promise<void>;
19
+ private readonly errorHandler;
20
+ /**
21
+ * Registers one or more route classes with the server.
22
+ * @param routeClasses - Route classes decorated with @Public or @Private.
23
+ */
24
+ registerRoutes(...routeClasses: Array<RouteConstructor>): void;
25
25
  /**
26
26
  * Adds middleware functions to the Express application.
27
27
  * @param handlers - Array of Express request handlers (middleware functions).
@@ -34,7 +34,9 @@ export declare class Server {
34
34
  getApp(): express.Express;
35
35
  /**
36
36
  * Starts the Express server.
37
+ * @param before Optional callback invoked before the server starts.
38
+ * @param after Optional callback invoked after the server has started.
37
39
  */
38
- start(): void;
40
+ start(before?: () => void | Promise<void>, after?: () => void | Promise<void>): Promise<void>;
39
41
  setAuthMiddleware(middleware: RequestHandler): void;
40
42
  }
package/dist/server.js CHANGED
@@ -1,50 +1,55 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Class representing an Express server that dynamically loads routes from a specified directory.
5
- */
6
- import fs from "fs";
7
- import path from "path";
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
8
10
  import express from "express";
9
11
  export class Server {
10
12
  /**
11
13
  * Creates an instance of the Server class.
12
14
  * @param port The port number on which the server will listen.
13
- * @param routesDirectory The directory where route files are located.
14
15
  * @param authMiddleware Optional authentication middleware to be used for private routes.
15
16
  */
16
- constructor(port, routesDirectory, authMiddleware) {
17
+ constructor(port, authMiddleware) {
18
+ /**
19
+ * Default error handler. Returns a generic 500 response, only including
20
+ * the error message and stack trace when NODE_ENV is "development".
21
+ */
22
+ this.errorHandler = (err, req, res, next) => {
23
+ if (res.headersSent) {
24
+ next(err);
25
+ return;
26
+ }
27
+ const isDevelopment = process.env.NODE_ENV === "development";
28
+ res.status(500).json(Object.assign({ error: "Internal Server Error" }, (isDevelopment && { message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : undefined })));
29
+ };
17
30
  this.port = port;
18
- this.routesDirectory = routesDirectory;
19
31
  this.app = express();
32
+ this.app.disable("x-powered-by");
20
33
  this.authMiddleware = authMiddleware;
21
34
  }
22
35
  /**
23
- * Loads all routes from the specified directory.
24
- * @returns Promise that resolves when all routes are loaded.
36
+ * Registers one or more route classes with the server.
37
+ * @param routeClasses - Route classes decorated with @Public or @Private.
25
38
  */
26
- async loadRoutes() {
27
- const routes = path.join(process.cwd(), this.routesDirectory);
28
- if (!fs.existsSync(routes)) {
29
- console.error(`Routes directory "${routes}" does not exist.`);
30
- return;
31
- }
32
- const files = fs.readdirSync(routes);
33
- await Promise.all(files.map(async (file) => {
34
- const modulePath = path.join(routes, file);
35
- const module = await import(modulePath);
36
- const RouteClass = module.default;
37
- // Pass authMiddleware to Route constructor
39
+ registerRoutes(...routeClasses) {
40
+ routeClasses.forEach((RouteClass) => {
38
41
  const routeInstance = new RouteClass(this.authMiddleware);
39
42
  this.app.use(routeInstance.router);
40
- }));
43
+ });
41
44
  }
42
45
  /**
43
46
  * Adds middleware functions to the Express application.
44
47
  * @param handlers - Array of Express request handlers (middleware functions).
45
48
  */
46
- async use(...handlers) {
47
- this.app.use(handlers);
49
+ use(...handlers) {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ this.app.use(handlers);
52
+ });
48
53
  }
49
54
  /**
50
55
  * Gets the Express application instance.
@@ -55,10 +60,23 @@ export class Server {
55
60
  }
56
61
  /**
57
62
  * Starts the Express server.
63
+ * @param before Optional callback invoked before the server starts.
64
+ * @param after Optional callback invoked after the server has started.
58
65
  */
59
- start() {
60
- this.app.listen(this.port, () => {
61
- console.log(`⚡ Server running on port: ${this.port}`);
66
+ start(before, after) {
67
+ return __awaiter(this, void 0, void 0, function* () {
68
+ if (before) {
69
+ yield before();
70
+ }
71
+ this.app.use(this.errorHandler);
72
+ yield new Promise((resolve) => {
73
+ this.app.listen(this.port, () => {
74
+ resolve();
75
+ });
76
+ });
77
+ if (after) {
78
+ yield after();
79
+ }
62
80
  });
63
81
  }
64
82
  setAuthMiddleware(middleware) {
package/eslint.config.mts CHANGED
@@ -48,28 +48,11 @@ export default defineConfig([
48
48
  }
49
49
  ],
50
50
  "@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports" }],
51
- "capitalized-comments": ["error", "always", { ignoreConsecutiveComments: true }],
52
51
  eqeqeq: ["error", "always"],
53
- "no-console": "warn",
54
- curly: ["error", "all"],
55
- "no-restricted-imports": [
56
- "error",
57
- {
58
- patterns: [".*"]
59
- }
60
- ],
61
52
  "import/order": [
62
53
  "error",
63
54
  {
64
55
  groups: ["builtin", "external", "internal", "parent", "sibling", "index", "object", "type"],
65
- pathGroups: [
66
- {
67
- pattern: "@/**",
68
- group: "internal",
69
- position: "before"
70
- }
71
- ],
72
- pathGroupsExcludedImportTypes: ["builtin"],
73
56
  "newlines-between": "never",
74
57
  alphabetize: {
75
58
  order: "asc",
@@ -78,11 +61,5 @@ export default defineConfig([
78
61
  }
79
62
  ]
80
63
  }
81
- },
82
- {
83
- files: ["test/**/*.{ts,mts,cts}"],
84
- rules: {
85
- "no-restricted-imports": "off"
86
- }
87
64
  }
88
65
  ]);
package/package.json CHANGED
@@ -1,14 +1,35 @@
1
1
  {
2
2
  "name": "@sjoblomtobias/relay",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
- "build": "tsc && tsc-alias"
7
+ "build": "tsc",
8
+ "dev": "tsx --watch test/index.ts",
9
+ "lint": "eslint src",
10
+ "format": "prettier --write src"
8
11
  },
9
12
  "author": "Tobias Sjöblom",
10
- "license": "MIT",
11
- "description": "",
13
+ "license": "Pirate",
14
+ "description": "A lightweight TypeScript framework for building structured Express applications with decorator-based routing and automatic route loading.",
15
+ "keywords": [
16
+ "express",
17
+ "typescript",
18
+ "framework",
19
+ "decorators",
20
+ "routing",
21
+ "rest",
22
+ "api",
23
+ "server"
24
+ ],
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/sjoblomtobias/relay.git"
28
+ },
29
+ "homepage": "https://github.com/sjoblomtobias/relay#readme",
30
+ "bugs": {
31
+ "url": "https://github.com/sjoblomtobias/relay/issues"
32
+ },
12
33
  "dependencies": {
13
34
  "express": "^5.1.0"
14
35
  },
@@ -25,11 +46,9 @@
25
46
  "eslint-plugin-prettier": "^5.5.4",
26
47
  "globals": "^16.4.0",
27
48
  "jiti": "^2.5.1",
28
- "nodemon": "^3.1.10",
29
49
  "prettier": "^3.6.2",
30
- "tsc-alias": "^1.8.16",
31
50
  "tsx": "^4.20.5",
32
51
  "typescript": "^5.9.2",
33
52
  "typescript-eslint": "^8.44.0"
34
53
  }
35
- }
54
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,2 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Entry point for the application.
5
- */
6
- export * from "@/route";
7
- export * from "@/server";
1
+ export * from "./route.js";
2
+ export * from "./server.js";
package/src/route.ts CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Base class for defining routes in an Express application.
5
- */
6
1
  import { Router } from "express";
7
2
  import type { Request, Response, NextFunction } from "express";
8
3
 
@@ -66,14 +61,12 @@ export abstract class Route {
66
61
  * Initializes the routes based on the implemented methods in the subclass.
67
62
  */
68
63
  protected initializeRoutes() {
64
+ if (this.isPrivate && !this.authMiddleware) {
65
+ throw new Error(`Route "${this.location}" is marked private but no authMiddleware was provided. Refusing to register it unprotected.`);
66
+ }
69
67
  this.getEndpoints().forEach(({ path, handler, routerMethod }) => {
70
68
  if (typeof handler === "function") {
71
- let handlers;
72
- if (this.isPrivate && this.authMiddleware) {
73
- handlers = [this.authMiddleware, handler.bind(this)];
74
- } else {
75
- handlers = [handler.bind(this)];
76
- }
69
+ const handlers = this.isPrivate && this.authMiddleware ? [this.authMiddleware, handler.bind(this)] : [handler.bind(this)];
77
70
  const fullPath = path ? `${this.location}${path}` : `${this.location}`;
78
71
  routerMethod(fullPath, ...handlers);
79
72
  }
package/src/server.ts CHANGED
@@ -1,55 +1,51 @@
1
- /**
2
- * @author Tobias Sjöblom
3
- * @since 1.0.0
4
- * @summary Class representing an Express server that dynamically loads routes from a specified directory.
5
- */
6
-
7
- import fs from "fs";
8
- import path from "path";
9
1
  import express from "express";
10
- import type { RequestHandler } from "express";
2
+ import type { Route } from "./route.js";
3
+ import type { ErrorRequestHandler, RequestHandler } from "express";
4
+
5
+ export type RouteConstructor = new (authMiddleware?: RequestHandler) => Route;
11
6
 
12
7
  export class Server {
13
8
  private port: number;
14
- private routesDirectory: string;
15
9
  private app: express.Express;
16
10
  private authMiddleware?: RequestHandler;
17
11
 
18
12
  /**
19
13
  * Creates an instance of the Server class.
20
14
  * @param port The port number on which the server will listen.
21
- * @param routesDirectory The directory where route files are located.
22
15
  * @param authMiddleware Optional authentication middleware to be used for private routes.
23
16
  */
24
- constructor(port: number, routesDirectory: string, authMiddleware?: RequestHandler) {
17
+ constructor(port: number, authMiddleware?: RequestHandler) {
25
18
  this.port = port;
26
- this.routesDirectory = routesDirectory;
27
19
  this.app = express();
20
+ this.app.disable("x-powered-by");
28
21
  this.authMiddleware = authMiddleware;
29
22
  }
30
23
 
31
24
  /**
32
- * Loads all routes from the specified directory.
33
- * @returns Promise that resolves when all routes are loaded.
25
+ * Default error handler. Returns a generic 500 response, only including
26
+ * the error message and stack trace when NODE_ENV is "development".
34
27
  */
35
- public async loadRoutes(): Promise<void> {
36
- const routes = path.join(process.cwd(), this.routesDirectory);
37
- if (!fs.existsSync(routes)) {
38
- console.error(`Routes directory "${routes}" does not exist.`);
28
+ private readonly errorHandler: ErrorRequestHandler = (err, req, res, next) => {
29
+ if (res.headersSent) {
30
+ next(err);
39
31
  return;
40
32
  }
41
- const files = fs.readdirSync(routes);
42
- await Promise.all(
43
- files.map(async (file) => {
44
- const modulePath = path.join(routes, file);
45
- const module = await import(modulePath);
46
- const RouteClass = module.default;
33
+ const isDevelopment = process.env.NODE_ENV === "development";
34
+ res.status(500).json({
35
+ error: "Internal Server Error",
36
+ ...(isDevelopment && { message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : undefined })
37
+ });
38
+ };
47
39
 
48
- // Pass authMiddleware to Route constructor
49
- const routeInstance = new RouteClass(this.authMiddleware);
50
- this.app.use(routeInstance.router);
51
- })
52
- );
40
+ /**
41
+ * Registers one or more route classes with the server.
42
+ * @param routeClasses - Route classes decorated with @Public or @Private.
43
+ */
44
+ public registerRoutes(...routeClasses: Array<RouteConstructor>): void {
45
+ routeClasses.forEach((RouteClass) => {
46
+ const routeInstance = new RouteClass(this.authMiddleware);
47
+ this.app.use(routeInstance.router);
48
+ });
53
49
  }
54
50
 
55
51
  /**
@@ -70,11 +66,22 @@ export class Server {
70
66
 
71
67
  /**
72
68
  * Starts the Express server.
69
+ * @param before Optional callback invoked before the server starts.
70
+ * @param after Optional callback invoked after the server has started.
73
71
  */
74
- public start(): void {
75
- this.app.listen(this.port, () => {
76
- console.log(`⚡ Server running on port: ${this.port}`);
72
+ public async start(before?: () => void | Promise<void>, after?: () => void | Promise<void>): Promise<void> {
73
+ if (before) {
74
+ await before();
75
+ }
76
+ this.app.use(this.errorHandler);
77
+ await new Promise<void>((resolve) => {
78
+ this.app.listen(this.port, () => {
79
+ resolve();
80
+ });
77
81
  });
82
+ if (after) {
83
+ await after();
84
+ }
78
85
  }
79
86
 
80
87
  public setAuthMiddleware(middleware: RequestHandler) {
package/test/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { Server } from "../src/server.js";
2
+ import HelloRoute from "./routes/hello.js";
3
+
4
+ const server = new Server(3000);
5
+
6
+ server.registerRoutes(HelloRoute);
7
+
8
+ server.start(
9
+ () => {
10
+ console.log("Before start: registering routes...");
11
+ },
12
+ () => {
13
+ console.log(`⚡ Server running on port: ${server["port"]}`);
14
+ }
15
+ );
@@ -0,0 +1,9 @@
1
+ import { Public, Route } from "../../src/route.js";
2
+ import type { Request, Response } from "express";
3
+
4
+ @Public("/hello")
5
+ export default class HelloRoute extends Route {
6
+ protected get(req: Request, res: Response): void {
7
+ res.json({ message: "Hello from relay!" });
8
+ }
9
+ }
package/tsconfig.json CHANGED
@@ -1,13 +1,9 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "baseUrl": ".",
4
3
  "rootDir": "src",
5
- "paths": {
6
- "@/*": ["./src/*"]
7
- },
8
- "moduleResolution": "node",
4
+ "moduleResolution": "bundler",
9
5
  "module": "esnext",
10
- "target": "ES2020",
6
+ "target": "es6",
11
7
  "esModuleInterop": true,
12
8
  "allowSyntheticDefaultImports": true,
13
9
  "strict": true,
@@ -21,9 +17,5 @@
21
17
  "declaration": true
22
18
  },
23
19
  "include": ["src/**/*"],
24
- "exclude": ["node_modules", "dist", "src/test"],
25
- "tsc-alias": {
26
- "resolveFullPaths": true,
27
- "verbose": true
28
- }
20
+ "exclude": ["node_modules", "dist", "src/test"]
29
21
  }