burger-api 0.1.4 → 0.2.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.
@@ -1,8 +1,8 @@
1
1
  // Import stuff from node
2
- import { readdirSync } from 'fs';
2
+ import { readdir } from 'fs/promises';
3
3
  import * as path from 'path';
4
4
  // Import utils
5
- import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
5
+ import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
6
6
  /**
7
7
  * ApiRouter class for handling file-based routing.
8
8
  * Loads routes from a directory structure and matches requests to the appropriate route handlers.
@@ -12,12 +12,13 @@ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, HTTP_METHOD
12
12
  export class ApiRouter {
13
13
  routesDir;
14
14
  prefix;
15
- /** Array of loaded route definitions */
16
- routes = [];
15
+ /** The root of the trie where all routes will begin*/
16
+ root = { children: new Map() };
17
17
  /**
18
18
  * Constructor for the ApiRouter class.
19
19
  * @param routesDir The directory path where route modules are located.
20
20
  * @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
21
+ * @throws {Error} If the routes directory path is not provided.
21
22
  */
22
23
  constructor(routesDir, prefix = '') {
23
24
  this.routesDir = routesDir;
@@ -27,17 +28,20 @@ export class ApiRouter {
27
28
  }
28
29
  }
29
30
  /**
30
- * Loads route modules from the specified directory and adds them to the routes array.
31
- * After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
32
- * @returns A promise that resolves when all route modules have been loaded and sorted.
33
- * @throws Error if the routes directory doesn't exist or can't be accessed
31
+ * Getter for the routes trie.
32
+ * @returns The root of the trie.
33
+ */
34
+ get routes() {
35
+ return this.root;
36
+ }
37
+ /**
38
+ * Loads all routes from the routes directory into the trie structure.
39
+ * @returns {Promise<void>} A promise that resolves when all routes are loaded.
40
+ * @throws {Error} If the routes directory is not found or if an error occurs during route loading.
34
41
  */
35
42
  async loadRoutes() {
36
43
  try {
37
- this.routes = [];
38
44
  await this.scanDirectory(this.routesDir);
39
- // Sort routes to ensure static routes are matched before dynamic ones
40
- this.routes.sort((a, b) => compareRoutes(a, b));
41
45
  }
42
46
  catch (error) {
43
47
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -45,16 +49,42 @@ export class ApiRouter {
45
49
  }
46
50
  }
47
51
  /**
48
- * Recursively scans the directory for route modules and adds them to the routes array.
49
- * @param dir The current directory to scan.
50
- * @param basePath The base path for constructing the route path.
51
- * @throws Error if multiple dynamic folders are found at the same level or if directory access fails
52
+ * Inserts a route definition into the trie structure.
53
+ * @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
54
+ * @throws {Error} If the route definition is invalid or causes a conflict in the trie.
55
+ */
56
+ insertRoute(routeDef) {
57
+ let node = this.root;
58
+ const segments = routeDef.path.split('/').filter(Boolean);
59
+ for (const segment of segments) {
60
+ if (segment.startsWith(':')) {
61
+ if (!node.paramChild) {
62
+ node.paramChild = { children: new Map() };
63
+ }
64
+ node = node.paramChild;
65
+ node.paramName = segment.slice(1);
66
+ }
67
+ else {
68
+ if (!node.children.has(segment)) {
69
+ node.children.set(segment, { children: new Map() });
70
+ }
71
+ node = node.children.get(segment);
72
+ }
73
+ }
74
+ node.route = routeDef;
75
+ }
76
+ /**
77
+ * Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
78
+ * @param dir The current directory path to scan.
79
+ * @param basePath The base path used to construct route paths from the directory structure.
80
+ * @returns {Promise<void>} A promise that resolves when the directory scan is complete.
81
+ * @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
52
82
  */
53
83
  async scanDirectory(dir, basePath = '') {
54
84
  // Track if a dynamic folder has been found at this directory level
55
85
  let dynamicFolderFound = false;
56
86
  try {
57
- const entries = readdirSync(dir, { withFileTypes: true });
87
+ const entries = await readdir(dir, { withFileTypes: true });
58
88
  for (const entry of entries) {
59
89
  const entryPath = path.join(dir, entry.name);
60
90
  const relativePath = path.join(basePath, entry.name);
@@ -82,24 +112,29 @@ export class ApiRouter {
82
112
  }
83
113
  }
84
114
  /**
85
- * Loads a route module and adds it to the routes array
86
- * @param entryPath Full path to the route file
87
- * @param relativePath Relative path used to construct the route
115
+ * Loads a route module from a file and inserts it into the trie.
116
+ * @param entryPath The full file system path to the route module (route.ts).
117
+ * @param relativePath The relative path used to construct the route path.
118
+ * @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
119
+ * @throws {Error} If the route module fails to load or is invalid.
88
120
  */
89
121
  async loadRouteModule(entryPath, relativePath) {
90
122
  try {
91
- // Convert file path to route path and load the module
123
+ // Convert the file path to a route path
92
124
  const routePath = this.convertFilePathToRoute(relativePath);
125
+ console.info('Loading route:', routePath);
126
+ // Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
93
127
  const modulePath = path.resolve(entryPath);
128
+ // Import the module
94
129
  const routeModule = await import(modulePath);
95
- // Collect HTTP method handlers from the module
130
+ // Variable to store the handlers for each method
96
131
  const handlers = {};
132
+ // Loop through all the HTTP methods and add the handler to the handlers object
97
133
  for (const method of HTTP_METHODS) {
98
134
  if (typeof routeModule[method] === 'function') {
99
135
  handlers[method] = routeModule[method];
100
136
  }
101
137
  }
102
- // Create route definition
103
138
  const routeDef = {
104
139
  path: routePath,
105
140
  handlers,
@@ -107,17 +142,16 @@ export class ApiRouter {
107
142
  schema: routeModule.schema,
108
143
  openapi: routeModule.openapi,
109
144
  };
110
- this.routes.push(routeDef);
145
+ this.insertRoute(routeDef);
111
146
  }
112
147
  catch (error) {
113
148
  throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
114
149
  }
115
150
  }
116
151
  /**
117
- * Converts a file path to a route path by processing dynamic segments,
118
- * removing certain directory indicators, and applying a prefix if specified.
119
- * @param filePath The file path to convert into a route path.
120
- * @returns The converted route path string.
152
+ * Converts a file path to a route path by processing dynamic segments and applying the prefix.
153
+ * @param filePath The file path to convert (e.g., "users/[id]/route.ts").
154
+ * @returns {string} The converted route path (e.g., "/users/:id").
121
155
  */
122
156
  convertFilePathToRoute(filePath) {
123
157
  // Remove the "route.ts" suffix
@@ -158,52 +192,38 @@ export class ApiRouter {
158
192
  return route;
159
193
  }
160
194
  /**
161
- * Resolves the given request by finding a matching route and extracting dynamic parameters.
162
- * @param request The request to resolve.
163
- * @returns An object containing the matched route and parameters, or an empty params object if no match.
195
+ * Resolves a request to a route definition and its parameters.
196
+ * @param pathname The normalized request pathname.
197
+ * @param method The uppercase HTTP method.
198
+ * @returns {{ route?: RouteDefinition; params: Record<string, string> }} An object containing the matched route (if any) and extracted parameters.
199
+ * @throws {Error} If the request URL is malformed.
164
200
  */
165
- resolve(request) {
201
+ resolve(pathname, method) {
166
202
  try {
167
- const url = new URL(request.url);
168
- const reqPath = normalizePath(url.pathname);
169
- const method = request.method.toUpperCase();
170
- for (const route of this.routes) {
171
- const match = this.matchRoute(reqPath, route.path);
172
- if (match && route.handlers[method]) {
173
- return { route, params: match };
203
+ const segments = pathname.split('/').filter(Boolean);
204
+ let node = this.root;
205
+ const params = {};
206
+ for (const segment of segments) {
207
+ if (node.children.has(segment)) {
208
+ node = node.children.get(segment);
209
+ }
210
+ else if (node.paramChild) {
211
+ node = node.paramChild;
212
+ params[node.paramName] = segment;
213
+ }
214
+ else {
215
+ return { params: {} };
174
216
  }
175
217
  }
218
+ if (node.route && node.route.handlers[method]) {
219
+ return { route: node.route, params };
220
+ }
176
221
  return { params: {} };
177
222
  }
178
223
  catch (error) {
179
- // Return no match in case of URL parsing errors
224
+ // Log the error for better debugging
225
+ console.error(`Error resolving API route for path "${pathname}":`, error);
180
226
  return { params: {} };
181
227
  }
182
228
  }
183
- /**
184
- * Checks if the request path matches the route path, extracting dynamic parameters if matched.
185
- * @param requestPath The request path to check.
186
- * @param routePath The route path to match against.
187
- * @returns A record of dynamic parameters if matched, otherwise null.
188
- */
189
- matchRoute(requestPath, routePath) {
190
- const reqSegments = requestPath.split('/').filter(Boolean);
191
- const routeSegments = routePath.split('/').filter(Boolean);
192
- if (reqSegments.length !== routeSegments.length) {
193
- return null;
194
- }
195
- const params = {};
196
- for (let i = 0; i < reqSegments.length; i++) {
197
- const rSegment = routeSegments[i];
198
- const reqSegment = reqSegments[i];
199
- if (rSegment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
200
- const paramName = rSegment.slice(1);
201
- params[paramName] = decodeURIComponent(reqSegment);
202
- }
203
- else if (rSegment !== reqSegment) {
204
- return null;
205
- }
206
- }
207
- return params;
208
- }
209
229
  }
@@ -1,12 +1,5 @@
1
- import type { ApiRouter } from './api-router.js';
2
- import type { ServerOptions } from '../types/index.js';
3
- /**
4
- * Generates an OpenAPI 3.0 document from the router's routes and global options.
5
- * @param router The router instance with loaded routes.
6
- * @param options Global options, including OpenAPI metadata.
7
- * @returns The OpenAPI document as a JavaScript object.
8
- */
9
- export declare function generateOpenAPIDocument(router: ApiRouter, options: ServerOptions): {
1
+ import type { ServerOptions, RouteDefinition } from '@burgerTypes';
2
+ export declare function generateOpenAPIDocument(apiRoutes: RouteDefinition[], options: ServerOptions): {
10
3
  openapi: string;
11
4
  info: {
12
5
  title: string;
@@ -67,13 +67,7 @@ function convertPathForOpenAPI(routePath) {
67
67
  // Replace occurrences of :param with {param}
68
68
  return routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
69
69
  }
70
- /**
71
- * Generates an OpenAPI 3.0 document from the router's routes and global options.
72
- * @param router The router instance with loaded routes.
73
- * @param options Global options, including OpenAPI metadata.
74
- * @returns The OpenAPI document as a JavaScript object.
75
- */
76
- export function generateOpenAPIDocument(router, options) {
70
+ export function generateOpenAPIDocument(apiRoutes, options) {
77
71
  const openapiDoc = {
78
72
  openapi: '3.0.0',
79
73
  info: {
@@ -83,9 +77,9 @@ export function generateOpenAPIDocument(router, options) {
83
77
  },
84
78
  paths: {},
85
79
  };
86
- // Iterate over each route in the router.
87
- for (const route of router.routes) {
88
- // Convert colon-based dynamic segments to OpenAPI's {param} syntax.
80
+ // Iterate over each route
81
+ for (const route of apiRoutes) {
82
+ // Convert colon-based dynamic segments to OpenAPI's {param} syntax
89
83
  const openApiPath = convertPathForOpenAPI(route.path);
90
84
  // Initialize path object if necessary
91
85
  openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
@@ -1,4 +1,4 @@
1
- import type { PageDefinition } from '../types/index.js';
1
+ import type { PageDefinition } from '@burgerTypes';
2
2
  /**
3
3
  * PageRouter class for handling file-based page routing.
4
4
  * Loads pages from a directory structure and matches requests to the appropriate page handlers.
@@ -1,4 +1,4 @@
1
- import type { ServerOptions, RequestHandler } from '../types/index.js';
1
+ import type { ServerOptions, FetchHandler } from '@burgerTypes';
2
2
  export declare class Server {
3
3
  private options;
4
4
  private server;
@@ -7,16 +7,9 @@ export declare class Server {
7
7
  * @param options - Configuration options for the server.
8
8
  */
9
9
  constructor(options: ServerOptions);
10
- /**
11
- * Starts the server with the given routes, handler, port, and callback.
12
- * @param routes - The routes to be used by the server.
13
- * @param handler - The handler to be used by the server.
14
- * @param port - The port to listen on.
15
- * @param cb - An optional callback function to be called when the server starts.
16
- */
17
10
  start(routes: {
18
11
  [key: string]: any;
19
- } | undefined, handler: RequestHandler, port: number, cb?: () => void): void;
12
+ } | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
20
13
  /**
21
14
  * Stops the server.
22
15
  * If the server is currently running, this method will stop the server and
@@ -1,8 +1,5 @@
1
1
  // Import stuff from Bun
2
2
  import { serve } from 'bun';
3
- // Import stuff from core
4
- import { HttpRequest } from './request.js';
5
- import { HttpResponse } from './response.js';
6
3
  // Import stuff from utils
7
4
  import { errorResponse } from '../utils/error.js';
8
5
  export class Server {
@@ -15,39 +12,37 @@ export class Server {
15
12
  constructor(options) {
16
13
  this.options = options;
17
14
  }
18
- /**
19
- * Starts the server with the given routes, handler, port, and callback.
20
- * @param routes - The routes to be used by the server.
21
- * @param handler - The handler to be used by the server.
22
- * @param port - The port to listen on.
23
- * @param cb - An optional callback function to be called when the server starts.
24
- */
25
15
  start(routes, handler, port, cb) {
26
16
  // Start Bun's native server using Bun.serve
27
17
  this.server = serve({
28
18
  routes,
29
- // Burger's fetch handler
19
+ // Bun's fetch handler
30
20
  fetch: async (request) => {
31
21
  try {
32
- // Wrap the native Request with HttpRequest to get a BurgerRequest
33
- const burgerReq = new HttpRequest(request);
34
- // Wrap the native Response with HttpResponse to get a BurgerResponse
35
- const burgerRes = new HttpResponse();
36
- // Invoke and return the handler with the wrapped requests and responses
37
- return await handler(burgerReq, burgerRes);
22
+ return await handler(request);
38
23
  }
39
24
  catch (error) {
40
25
  // Return a custom error response
41
26
  return errorResponse(error, request, this.options.debug ?? false);
42
27
  }
43
28
  },
29
+ // Global error handler
30
+ error(error) {
31
+ console.error(error);
32
+ return new Response(`Internal Server Error: ${error.message}`, {
33
+ status: 500,
34
+ headers: {
35
+ 'Content-Type': 'text/plain',
36
+ },
37
+ });
38
+ },
44
39
  port,
45
40
  });
46
41
  if (cb) {
47
42
  cb();
48
43
  }
49
44
  else {
50
- console.log(`✔ Server started on port: ${port}`);
45
+ console.log(`🍔 BurgerAPI is running at: http://${this.options.hostname || 'localhost'}:${port}`);
51
46
  }
52
47
  }
53
48
  /**
@@ -1,10 +1,42 @@
1
- import type { ServerOptions, Middleware } from './types/index.js';
1
+ import type { ServerOptions } from '@burgerTypes';
2
2
  export declare class Burger {
3
3
  private options;
4
+ /**
5
+ * The server instance
6
+ */
4
7
  private server;
8
+ /**
9
+ * The API router instance
10
+ */
5
11
  private apiRouter?;
12
+ /**
13
+ * The page router instance
14
+ */
6
15
  private pageRouter?;
16
+ /**
17
+ * The global middleware
18
+ */
7
19
  private globalMiddleware;
20
+ /**
21
+ * The OpenAPI document
22
+ */
23
+ private openApiDoc;
24
+ /**
25
+ * The routes object
26
+ */
27
+ private routes;
28
+ /**
29
+ * Pre-computed responses for reuse
30
+ */
31
+ private readonly METHOD_NOT_ALLOWED;
32
+ /**
33
+ * The not found response
34
+ */
35
+ private readonly NOT_FOUND;
36
+ /**
37
+ * The OpenAPI error response
38
+ */
39
+ private readonly OPENAPI_ERROR;
8
40
  /**
9
41
  * Constructor for the Burger class.
10
42
  * @param options - The options for the server and router.
@@ -16,10 +48,23 @@ export declare class Burger {
16
48
  */
17
49
  constructor(options: ServerOptions);
18
50
  /**
19
- * Adds a global middleware function to the list of middlewares.
20
- * @param mw - The middleware function to add.
51
+ * Process the page routes and add them to the routes object
52
+ * @returns A promise that resolves to a boolean
53
+ */
54
+ private processPageRoutes;
55
+ /**
56
+ * Process the API routes and add them to the routes object
57
+ * @returns A promise that resolves to a boolean
58
+ */
59
+ private processApiRoutes;
60
+ /**
61
+ * Process the middleware and handler
62
+ * @param request - The request object
63
+ * @param middlewares - The middleware array
64
+ * @param handler - The handler function
65
+ * @returns A promise that resolves to a response
21
66
  */
22
- addGlobalMiddleware(mw: Middleware): void;
67
+ private processMiddleware;
23
68
  /**
24
69
  * Starts the server and begins listening for incoming requests.
25
70
  * @param port - The port number to listen on. Defaults to `4000`.
@@ -29,4 +74,4 @@ export declare class Burger {
29
74
  serve(port?: number, cb?: () => void): Promise<void>;
30
75
  }
31
76
  export { setDir } from './utils/index.js';
32
- export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, BurgerNext, Middleware, openapi, } from './types/index.js';
77
+ export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, BurgerNext, Middleware, openapi, } from '@burgerTypes';