@sjoblomtobias/relay 1.0.2 → 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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # relay
2
2
 
3
- A lightweight TypeScript framework for building structured Express applications with decorator-based routing and automatic route loading.
3
+ A lightweight TypeScript framework for building structured Express applications with decorator-based routing.
4
4
 
5
5
  ## Installation
6
6
 
@@ -17,27 +17,27 @@ Extend the `Route` class and decorate it with `@Public` or `@Private`. Override
17
17
  ```ts
18
18
  // src/routes/users.ts
19
19
  import { Public, Route } from "@sjoblomtobias/relay";
20
- import type { Request, Response } from "express";
20
+ import type { Request, Response, NextFunction } from "express";
21
21
 
22
22
  @Public("/users")
23
23
  export default class UsersRoute extends Route {
24
- protected get(req: Request, res: Response): void {
24
+ protected get(req: Request, res: Response, next: NextFunction): void {
25
25
  res.json([{ id: 1, name: "Alice" }]);
26
26
  }
27
27
 
28
- protected getById(req: Request, res: Response): void {
28
+ protected getById(req: Request, res: Response, next: NextFunction): void {
29
29
  res.json({ id: req.params.id });
30
30
  }
31
31
 
32
- protected post(req: Request, res: Response): void {
32
+ protected post(req: Request, res: Response, next: NextFunction): void {
33
33
  res.status(201).json(req.body);
34
34
  }
35
35
 
36
- protected patch(req: Request, res: Response): void {
36
+ protected patch(req: Request, res: Response, next: NextFunction): void {
37
37
  res.json({ id: req.params.id, ...req.body });
38
38
  }
39
39
 
40
- protected delete(req: Request, res: Response): void {
40
+ protected delete(req: Request, res: Response, next: NextFunction): void {
41
41
  res.status(204).send();
42
42
  }
43
43
  }
@@ -51,28 +51,27 @@ export default class UsersRoute extends Route {
51
51
  | `@Private(path)` | Registers the route at `path`, applies `authMiddleware` if provided |
52
52
  | `@Location(path, isPrivate?)` | Base decorator used by `@Public` and `@Private` |
53
53
 
54
- ### 3. Start the server
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.
55
57
 
56
58
  ```ts
57
59
  // src/index.ts
58
60
  import { Server } from "@sjoblomtobias/relay";
61
+ import UsersRoute from "./routes/users.js";
59
62
 
60
- const server = new Server(3000, "routes");
63
+ const server = new Server(3000);
61
64
 
62
- await server.start(
63
- async () => {
64
- // Runs before the server binds — load routes, connect to DB, etc.
65
- await server.loadRoutes(import.meta.dirname);
66
- },
67
- () => {
68
- console.log("Ready!");
69
- }
70
- );
65
+ server.registerRoutes(UsersRoute);
66
+
67
+ await server.start(undefined, () => {
68
+ console.log("Ready!");
69
+ });
71
70
  ```
72
71
 
73
72
  ### 4. Authentication middleware
74
73
 
75
- Pass an Express `RequestHandler` as the third argument to `Server`. It will be applied to all routes decorated with `@Private`.
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`.
76
75
 
77
76
  ```ts
78
77
  import { Server } from "@sjoblomtobias/relay";
@@ -82,13 +81,14 @@ const authMiddleware = (req, res, next) => {
82
81
  next();
83
82
  };
84
83
 
85
- const server = new Server(3000, "routes", authMiddleware);
84
+ const server = new Server(3000, authMiddleware);
86
85
  ```
87
86
 
88
- You can also set or update it later:
87
+ You can also set it separately, as long as it happens before `registerRoutes`:
89
88
 
90
89
  ```ts
91
90
  server.setAuthMiddleware(authMiddleware);
91
+ server.registerRoutes(UsersRoute);
92
92
  ```
93
93
 
94
94
  ## API
@@ -97,12 +97,12 @@ server.setAuthMiddleware(authMiddleware);
97
97
 
98
98
  | Method | Description |
99
99
  |--------|-------------|
100
- | `new Server(port, routesDir, authMiddleware?)` | Creates a new server instance |
101
- | `loadRoutes(baseDir?)` | Dynamically imports all route files from `baseDir/routesDir`. Defaults `baseDir` to `process.cwd()` |
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
102
  | `start(before?, after?)` | Starts the server. Awaits optional `before` callback, binds the port, then awaits optional `after` callback |
103
103
  | `use(...handlers)` | Adds Express middleware |
104
104
  | `getApp()` | Returns the underlying Express app |
105
- | `setAuthMiddleware(middleware)` | Sets or replaces the authentication middleware |
105
+ | `setAuthMiddleware(middleware)` | Sets or replaces the authentication middleware. Must be called before `registerRoutes` for any `@Private` route |
106
106
 
107
107
  ### `Route`
108
108
 
@@ -118,6 +118,31 @@ Abstract base class. Override any of the following optional methods:
118
118
 
119
119
  Override `getEndpoints()` to fully customize the endpoint configuration.
120
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
+
121
146
  ## License
122
147
 
123
148
  Pirate
package/dist/route.js CHANGED
@@ -44,15 +44,12 @@ export class Route {
44
44
  * Initializes the routes based on the implemented methods in the subclass.
45
45
  */
46
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
+ }
47
50
  this.getEndpoints().forEach(({ path, handler, routerMethod }) => {
48
51
  if (typeof handler === "function") {
49
- let handlers;
50
- if (this.isPrivate && this.authMiddleware) {
51
- handlers = [this.authMiddleware, handler.bind(this)];
52
- }
53
- else {
54
- handlers = [handler.bind(this)];
55
- }
52
+ const handlers = this.isPrivate && this.authMiddleware ? [this.authMiddleware, handler.bind(this)] : [handler.bind(this)];
56
53
  const fullPath = path ? `${this.location}${path}` : `${this.location}`;
57
54
  routerMethod(fullPath, ...handlers);
58
55
  }
package/dist/server.d.ts CHANGED
@@ -1,23 +1,27 @@
1
1
  import express from "express";
2
+ import type { Route } from "./route.js";
2
3
  import type { RequestHandler } from "express";
4
+ export type RouteConstructor = new (authMiddleware?: RequestHandler) => Route;
3
5
  export declare class Server {
4
6
  private port;
5
- private routesDirectory;
6
7
  private app;
7
8
  private authMiddleware?;
8
9
  /**
9
10
  * Creates an instance of the Server class.
10
11
  * @param port The port number on which the server will listen.
11
- * @param routesDirectory The directory where route files are located.
12
12
  * @param authMiddleware Optional authentication middleware to be used for private routes.
13
13
  */
14
- constructor(port: number, routesDirectory: string, authMiddleware?: RequestHandler);
14
+ constructor(port: number, authMiddleware?: RequestHandler);
15
15
  /**
16
- * Loads all routes from the specified directory.
17
- * @param baseDir The base directory to resolve the routes directory from. Defaults to process.cwd().
18
- * @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".
19
18
  */
20
- loadRoutes(baseDir?: string): 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;
21
25
  /**
22
26
  * Adds middleware functions to the Express application.
23
27
  * @param handlers - Array of Express request handlers (middleware functions).
package/dist/server.js CHANGED
@@ -7,43 +7,39 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import fs from "fs";
11
- import path from "path";
12
10
  import express from "express";
13
11
  export class Server {
14
12
  /**
15
13
  * Creates an instance of the Server class.
16
14
  * @param port The port number on which the server will listen.
17
- * @param routesDirectory The directory where route files are located.
18
15
  * @param authMiddleware Optional authentication middleware to be used for private routes.
19
16
  */
20
- 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
+ };
21
30
  this.port = port;
22
- this.routesDirectory = routesDirectory;
23
31
  this.app = express();
32
+ this.app.disable("x-powered-by");
24
33
  this.authMiddleware = authMiddleware;
25
34
  }
26
35
  /**
27
- * Loads all routes from the specified directory.
28
- * @param baseDir The base directory to resolve the routes directory from. Defaults to process.cwd().
29
- * @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.
30
38
  */
31
- loadRoutes() {
32
- return __awaiter(this, arguments, void 0, function* (baseDir = process.cwd()) {
33
- const routes = path.join(baseDir, this.routesDirectory);
34
- if (!fs.existsSync(routes)) {
35
- console.error(`Routes directory "${routes}" does not exist.`);
36
- return;
37
- }
38
- const files = fs.readdirSync(routes);
39
- yield Promise.all(files.map((file) => __awaiter(this, void 0, void 0, function* () {
40
- const modulePath = path.join(routes, file);
41
- const module = yield import(modulePath);
42
- const RouteClass = module.default;
43
- // Pass authMiddleware to Route constructor
44
- const routeInstance = new RouteClass(this.authMiddleware);
45
- this.app.use(routeInstance.router);
46
- })));
39
+ registerRoutes(...routeClasses) {
40
+ routeClasses.forEach((RouteClass) => {
41
+ const routeInstance = new RouteClass(this.authMiddleware);
42
+ this.app.use(routeInstance.router);
47
43
  });
48
44
  }
49
45
  /**
@@ -72,6 +68,7 @@ export class Server {
72
68
  if (before) {
73
69
  yield before();
74
70
  }
71
+ this.app.use(this.errorHandler);
75
72
  yield new Promise((resolve) => {
76
73
  this.app.listen(this.port, () => {
77
74
  resolve();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjoblomtobias/relay",
3
- "version": "1.0.2",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -12,6 +12,24 @@
12
12
  "author": "Tobias Sjöblom",
13
13
  "license": "Pirate",
14
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
+ },
15
33
  "dependencies": {
16
34
  "express": "^5.1.0"
17
35
  },
package/src/route.ts CHANGED
@@ -61,14 +61,12 @@ export abstract class Route {
61
61
  * Initializes the routes based on the implemented methods in the subclass.
62
62
  */
63
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
+ }
64
67
  this.getEndpoints().forEach(({ path, handler, routerMethod }) => {
65
68
  if (typeof handler === "function") {
66
- let handlers;
67
- if (this.isPrivate && this.authMiddleware) {
68
- handlers = [this.authMiddleware, handler.bind(this)];
69
- } else {
70
- handlers = [handler.bind(this)];
71
- }
69
+ const handlers = this.isPrivate && this.authMiddleware ? [this.authMiddleware, handler.bind(this)] : [handler.bind(this)];
72
70
  const fullPath = path ? `${this.location}${path}` : `${this.location}`;
73
71
  routerMethod(fullPath, ...handlers);
74
72
  }
package/src/server.ts CHANGED
@@ -1,49 +1,51 @@
1
- import fs from "fs";
2
- import path from "path";
3
1
  import express from "express";
4
- 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;
5
6
 
6
7
  export class Server {
7
8
  private port: number;
8
- private routesDirectory: string;
9
9
  private app: express.Express;
10
10
  private authMiddleware?: RequestHandler;
11
11
 
12
12
  /**
13
13
  * Creates an instance of the Server class.
14
14
  * @param port The port number on which the server will listen.
15
- * @param routesDirectory The directory where route files are located.
16
15
  * @param authMiddleware Optional authentication middleware to be used for private routes.
17
16
  */
18
- constructor(port: number, routesDirectory: string, authMiddleware?: RequestHandler) {
17
+ constructor(port: number, authMiddleware?: RequestHandler) {
19
18
  this.port = port;
20
- this.routesDirectory = routesDirectory;
21
19
  this.app = express();
20
+ this.app.disable("x-powered-by");
22
21
  this.authMiddleware = authMiddleware;
23
22
  }
24
23
 
25
24
  /**
26
- * Loads all routes from the specified directory.
27
- * @param baseDir The base directory to resolve the routes directory from. Defaults to process.cwd().
28
- * @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".
29
27
  */
30
- public async loadRoutes(baseDir: string = process.cwd()): Promise<void> {
31
- const routes = path.join(baseDir, this.routesDirectory);
32
- if (!fs.existsSync(routes)) {
33
- throw new Error(`Routes directory "${routes}" does not exist.`);
28
+ private readonly errorHandler: ErrorRequestHandler = (err, req, res, next) => {
29
+ if (res.headersSent) {
30
+ next(err);
31
+ return;
34
32
  }
35
- const files = fs.readdirSync(routes);
36
- await Promise.all(
37
- files.map(async (file) => {
38
- const modulePath = path.join(routes, file);
39
- const module = await import(modulePath);
40
- 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
+ };
41
39
 
42
- // Pass authMiddleware to Route constructor
43
- const routeInstance = new RouteClass(this.authMiddleware);
44
- this.app.use(routeInstance.router);
45
- })
46
- );
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
+ });
47
49
  }
48
50
 
49
51
  /**
@@ -71,6 +73,7 @@ export class Server {
71
73
  if (before) {
72
74
  await before();
73
75
  }
76
+ this.app.use(this.errorHandler);
74
77
  await new Promise<void>((resolve) => {
75
78
  this.app.listen(this.port, () => {
76
79
  resolve();
package/test/index.ts CHANGED
@@ -1,13 +1,15 @@
1
1
  import { Server } from "../src/server.js";
2
+ import HelloRoute from "./routes/hello.js";
2
3
 
3
- const server = new Server(3000, "routes");
4
+ const server = new Server(3000);
5
+
6
+ server.registerRoutes(HelloRoute);
4
7
 
5
8
  server.start(
6
9
  () => {
7
- console.log("Before start: loading routes...");
8
- return server.loadRoutes(import.meta.dirname);
10
+ console.log("Before start: registering routes...");
9
11
  },
10
12
  () => {
11
- console.log(`⚡ Server running on port: ${server['port']}`);
13
+ console.log(`⚡ Server running on port: ${server["port"]}`);
12
14
  }
13
15
  );
Binary file