@vyriy/router 0.2.1 → 0.3.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
@@ -9,6 +9,7 @@ This package provides a small API Gateway router for Lambda handlers.
9
9
  It is intentionally kept small:
10
10
 
11
11
  - matches by HTTP method and exact path
12
+ - supports simple prefix dispatch for handler factories such as static file serving
12
13
  - passes API Gateway event data into handlers
13
14
  - returns a Lambda-friendly response shape
14
15
 
@@ -32,6 +33,7 @@ yarn add @vyriy/router
32
33
 
33
34
  ```ts
34
35
  import { createRouter } from '@vyriy/router';
36
+ import { staticFiles } from '@vyriy/server/static';
35
37
 
36
38
  const router = createRouter();
37
39
 
@@ -46,6 +48,26 @@ router.get('/health', async ({ event, query, headers, pathParameters, body }) =>
46
48
  body,
47
49
  }),
48
50
  }));
51
+
52
+ router.prefix('/static', staticFiles('./public'));
53
+
54
+ router.fallback(async ({ event }) => ({
55
+ statusCode: 404,
56
+ body: JSON.stringify({
57
+ message: 'Not Found',
58
+ path: event.path,
59
+ }),
60
+ }));
61
+ ```
62
+
63
+ Prefix handlers receive the relative matched path in `pathParameters.proxy`, so they can behave like normal handlers:
64
+
65
+ ```ts
66
+ router.prefix('/events', async ({ pathParameters, responseStream }) => {
67
+ responseStream?.setContentType?.('text/plain');
68
+ responseStream?.write(`Path: ${pathParameters?.proxy}`);
69
+ responseStream?.end();
70
+ });
49
71
  ```
50
72
 
51
73
  ## Exports
@@ -65,11 +87,15 @@ import { Router } from '@vyriy/router/router';
65
87
  - `router.put(path, handler)` registers a `PUT` handler.
66
88
  - `router.delete(path, handler)` registers a `DELETE` handler.
67
89
  - `router.patch(path, handler)` registers a `PATCH` handler.
90
+ - `router.prefix(pathPrefix, handler)` registers a handler for every request under a URL prefix.
91
+ - `router.fallback(handler)` registers a handler for unmatched requests.
68
92
  - `router.route(event)` resolves the matching route and returns an API Gateway response.
69
93
 
70
94
  The low-level `Router` class is also available from `@vyriy/router/router` and exposes only:
71
95
 
72
96
  - `router.on(method, path, handler)`
97
+ - `router.prefix(pathPrefix, handler)`
98
+ - `router.fallback(handler)`
73
99
  - `router.route(event)`
74
100
 
75
101
  Route handlers receive:
@@ -80,6 +106,7 @@ type HandlerParams = {
80
106
  body?: string;
81
107
  headers?: APIGatewayProxyEvent['headers'];
82
108
  pathParameters?: APIGatewayProxyEvent['pathParameters'];
109
+ responseStream?: ResponseStream;
83
110
  event: APIGatewayProxyEvent;
84
111
  };
85
112
  ```
package/create.js CHANGED
@@ -18,10 +18,18 @@ export const createRouter = () => {
18
18
  router.on('DELETE', path, handler);
19
19
  return api;
20
20
  },
21
+ fallback(handler) {
22
+ router.fallback(handler);
23
+ return api;
24
+ },
21
25
  patch(path, handler) {
22
26
  router.on('PATCH', path, handler);
23
27
  return api;
24
28
  },
29
+ prefix(pathPrefix, handler) {
30
+ router.prefix(pathPrefix, handler);
31
+ return api;
32
+ },
25
33
  route(event) {
26
34
  return router.route(event);
27
35
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vyriy/router",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Router utility for Vyriy projects",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/router.d.ts CHANGED
@@ -1,6 +1,10 @@
1
- import type { APIGatewayProxyEvent, APIGatewayProxyResult, Handler } from './types.js';
1
+ import type { APIGatewayProxyEvent, Handler, ResponseStream, RouteResult } from './types.js';
2
2
  export declare class Router {
3
+ private fallbackHandler?;
3
4
  private readonly routes;
5
+ private readonly staticRoutes;
4
6
  on(method: string, path: string, handler: Handler): this;
5
- route(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult>;
7
+ fallback(handler: Handler): this;
8
+ prefix(pathPrefix: string, handler: Handler): this;
9
+ route(event: APIGatewayProxyEvent, responseStream?: ResponseStream): Promise<RouteResult | void>;
6
10
  }
package/router.js CHANGED
@@ -1,7 +1,36 @@
1
1
  import { METHODS, STATUS_CODES } from 'node:http';
2
2
  const SUPPORTED_METHODS = new Set(METHODS.map((method) => method.toUpperCase()));
3
+ const removeLeadingSlashes = (value) => {
4
+ let start = 0;
5
+ while (value[start] === '/') {
6
+ start += 1;
7
+ }
8
+ return value.slice(start);
9
+ };
10
+ const removeTrailingSlashes = (value) => {
11
+ let end = value.length;
12
+ while (end > 0 && value[end - 1] === '/') {
13
+ end -= 1;
14
+ }
15
+ return value.slice(0, end);
16
+ };
17
+ const getPrefixPath = (eventPath, route) => {
18
+ if (eventPath !== route.pathPrefix && !eventPath.startsWith(`${route.pathPrefix}/`)) {
19
+ return undefined;
20
+ }
21
+ return decodeURIComponent(removeLeadingSlashes(eventPath.slice(route.pathPrefix.length)));
22
+ };
23
+ const normalizeResult = (result) => ({
24
+ statusCode: result.statusCode ?? 200,
25
+ body: result.body,
26
+ headers: result.headers,
27
+ isBase64Encoded: result.isBase64Encoded,
28
+ multiValueHeaders: result.multiValueHeaders,
29
+ });
3
30
  export class Router {
31
+ fallbackHandler;
4
32
  routes = {};
33
+ staticRoutes = [];
5
34
  on(method, path, handler) {
6
35
  const normalizedMethod = method.toUpperCase();
7
36
  if (!SUPPORTED_METHODS.has(normalizedMethod)) {
@@ -14,26 +43,67 @@ export class Router {
14
43
  routeGroup[path] = handler;
15
44
  return this;
16
45
  }
17
- async route(event) {
18
- const { httpMethod, path, queryStringParameters, body, headers, pathParameters } = event;
19
- const result = await this.routes[httpMethod]?.[path]?.({
20
- query: queryStringParameters ?? undefined,
21
- body: body ?? undefined,
22
- headers,
23
- pathParameters: pathParameters ?? undefined,
24
- event,
46
+ fallback(handler) {
47
+ this.fallbackHandler = handler;
48
+ return this;
49
+ }
50
+ prefix(pathPrefix, handler) {
51
+ this.staticRoutes.push({
52
+ handler,
53
+ pathPrefix: removeTrailingSlashes(pathPrefix) || '/',
25
54
  });
26
- return result
27
- ? {
28
- statusCode: result.statusCode ?? 200,
29
- body: result.body,
30
- headers: result.headers,
55
+ return this;
56
+ }
57
+ async route(event, responseStream) {
58
+ const { httpMethod, path, queryStringParameters, body, headers, pathParameters } = event;
59
+ const exactHandler = this.routes[httpMethod]?.[path];
60
+ if (exactHandler) {
61
+ const result = await exactHandler({
62
+ query: queryStringParameters ?? undefined,
63
+ body: body ?? undefined,
64
+ headers,
65
+ pathParameters: pathParameters ?? undefined,
66
+ responseStream,
67
+ event,
68
+ });
69
+ return result ? normalizeResult(result) : undefined;
70
+ }
71
+ for (const staticRoute of this.staticRoutes) {
72
+ const proxy = getPrefixPath(path, staticRoute);
73
+ if (proxy !== undefined) {
74
+ const prefixResult = await staticRoute.handler({
75
+ query: queryStringParameters ?? undefined,
76
+ body: body ?? undefined,
77
+ headers,
78
+ pathParameters: {
79
+ ...pathParameters,
80
+ proxy,
81
+ },
82
+ responseStream,
83
+ event,
84
+ });
85
+ if (prefixResult) {
86
+ return normalizeResult(prefixResult);
87
+ }
88
+ return undefined;
31
89
  }
32
- : {
33
- statusCode: 404,
34
- body: JSON.stringify({
35
- message: STATUS_CODES[404],
36
- }),
37
- };
90
+ }
91
+ if (this.fallbackHandler) {
92
+ const fallbackResult = await this.fallbackHandler({
93
+ query: queryStringParameters ?? undefined,
94
+ body: body ?? undefined,
95
+ headers,
96
+ pathParameters: pathParameters ?? undefined,
97
+ responseStream,
98
+ event,
99
+ });
100
+ return fallbackResult ? normalizeResult(fallbackResult) : undefined;
101
+ }
102
+ return {
103
+ statusCode: 404,
104
+ body: JSON.stringify({
105
+ message: STATUS_CODES[404],
106
+ }),
107
+ };
38
108
  }
39
109
  }
package/types.d.ts CHANGED
@@ -1,23 +1,37 @@
1
1
  import type { APIGatewayProxyEvent, APIGatewayProxyEventQueryStringParameters, APIGatewayProxyResult } from 'aws-lambda';
2
2
  export type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
3
- export type Result = {
3
+ export type RouteResult = {
4
4
  body: APIGatewayProxyResult['body'];
5
5
  headers?: APIGatewayProxyResult['headers'];
6
+ isBase64Encoded?: APIGatewayProxyResult['isBase64Encoded'];
7
+ multiValueHeaders?: APIGatewayProxyResult['multiValueHeaders'];
6
8
  statusCode?: APIGatewayProxyResult['statusCode'];
7
9
  };
10
+ export type ResponseStream = {
11
+ end: {
12
+ (): unknown;
13
+ (chunk: string | Buffer | Uint8Array): unknown;
14
+ };
15
+ setContentType?: (contentType: string) => unknown;
16
+ writableEnded?: boolean;
17
+ write(chunk: string | Buffer | Uint8Array): unknown;
18
+ };
8
19
  export type HandlerParams = {
9
20
  query?: APIGatewayProxyEventQueryStringParameters;
10
21
  body?: string;
11
22
  headers?: APIGatewayProxyEvent['headers'];
12
23
  pathParameters?: APIGatewayProxyEvent['pathParameters'];
24
+ responseStream?: ResponseStream;
13
25
  event: APIGatewayProxyEvent;
14
26
  };
15
- export type Handler = (params: HandlerParams) => Promise<Result | undefined>;
27
+ export type Handler = (params: HandlerParams) => Promise<RouteResult | void>;
16
28
  export type RouterApi = {
17
29
  get(path: string, handler: Handler): RouterApi;
18
30
  post(path: string, handler: Handler): RouterApi;
19
31
  put(path: string, handler: Handler): RouterApi;
20
32
  delete(path: string, handler: Handler): RouterApi;
33
+ fallback(handler: Handler): RouterApi;
21
34
  patch(path: string, handler: Handler): RouterApi;
22
- route(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult>;
35
+ prefix(pathPrefix: string, handler: Handler): RouterApi;
36
+ route(event: APIGatewayProxyEvent, responseStream?: ResponseStream): Promise<RouteResult | void>;
23
37
  };