burger-api 0.1.0 → 0.1.4
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 +278 -246
- package/dist/src/core/api-router.d.ts +1 -1
- package/dist/src/core/api-router.js +15 -15
- package/dist/src/core/openapi.d.ts +2 -2
- package/dist/src/core/openapi.js +17 -17
- package/dist/src/core/page-router.d.ts +1 -1
- package/dist/src/core/page-router.js +20 -19
- package/dist/src/core/response.js +6 -6
- package/dist/src/core/server.d.ts +4 -2
- package/dist/src/core/server.js +8 -5
- package/dist/src/index.d.ts +3 -3
- package/dist/src/index.js +48 -39
- package/dist/src/middleware/validator.d.ts +1 -1
- package/dist/src/middleware/validator.js +9 -6
- package/dist/src/types/index.d.ts +8 -2
- package/dist/src/types/index.js +1 -1
- package/dist/src/utils/error.js +9 -9
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +6 -6
- package/dist/src/utils/routing.d.ts +1 -1
- package/dist/src/utils/routing.js +15 -15
- package/package.json +83 -82
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RouteDefinition } from
|
|
1
|
+
import type { RouteDefinition } from '../types/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* ApiRouter class for handling file-based routing.
|
|
4
4
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Import stuff from node
|
|
2
|
-
import { readdirSync } from
|
|
3
|
-
import * as path from
|
|
2
|
+
import { readdirSync } from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, HTTP_METHODS, } from
|
|
5
|
+
import { cleanPrefix, normalizePath, compareRoutes, 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.
|
|
@@ -19,11 +19,11 @@ export class ApiRouter {
|
|
|
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
21
|
*/
|
|
22
|
-
constructor(routesDir, prefix =
|
|
22
|
+
constructor(routesDir, prefix = '') {
|
|
23
23
|
this.routesDir = routesDir;
|
|
24
24
|
this.prefix = prefix;
|
|
25
25
|
if (!routesDir) {
|
|
26
|
-
throw new Error(
|
|
26
|
+
throw new Error('Routes directory path is required');
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
/**
|
|
@@ -50,7 +50,7 @@ export class ApiRouter {
|
|
|
50
50
|
* @param basePath The base path for constructing the route path.
|
|
51
51
|
* @throws Error if multiple dynamic folders are found at the same level or if directory access fails
|
|
52
52
|
*/
|
|
53
|
-
async scanDirectory(dir, basePath =
|
|
53
|
+
async scanDirectory(dir, basePath = '') {
|
|
54
54
|
// Track if a dynamic folder has been found at this directory level
|
|
55
55
|
let dynamicFolderFound = false;
|
|
56
56
|
try {
|
|
@@ -69,7 +69,7 @@ export class ApiRouter {
|
|
|
69
69
|
}
|
|
70
70
|
await this.scanDirectory(entryPath, relativePath);
|
|
71
71
|
}
|
|
72
|
-
else if (entry.isFile() && entry.name ===
|
|
72
|
+
else if (entry.isFile() && entry.name === 'route.ts') {
|
|
73
73
|
await this.loadRouteModule(entryPath, relativePath);
|
|
74
74
|
}
|
|
75
75
|
}
|
|
@@ -95,7 +95,7 @@ export class ApiRouter {
|
|
|
95
95
|
// Collect HTTP method handlers from the module
|
|
96
96
|
const handlers = {};
|
|
97
97
|
for (const method of HTTP_METHODS) {
|
|
98
|
-
if (typeof routeModule[method] ===
|
|
98
|
+
if (typeof routeModule[method] === 'function') {
|
|
99
99
|
handlers[method] = routeModule[method];
|
|
100
100
|
}
|
|
101
101
|
}
|
|
@@ -121,8 +121,8 @@ export class ApiRouter {
|
|
|
121
121
|
*/
|
|
122
122
|
convertFilePathToRoute(filePath) {
|
|
123
123
|
// Remove the "route.ts" suffix
|
|
124
|
-
if (filePath.endsWith(
|
|
125
|
-
filePath = filePath.slice(0, -
|
|
124
|
+
if (filePath.endsWith('route.ts')) {
|
|
125
|
+
filePath = filePath.slice(0, -'route.ts'.length);
|
|
126
126
|
}
|
|
127
127
|
// Split path into segments
|
|
128
128
|
const segments = filePath.split(path.sep);
|
|
@@ -145,14 +145,14 @@ export class ApiRouter {
|
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
// Construct the route with leading slash
|
|
148
|
-
let route =
|
|
148
|
+
let route = '/' + resultSegments.join('/');
|
|
149
149
|
// Apply prefix if provided
|
|
150
150
|
if (this.prefix) {
|
|
151
151
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
152
|
-
route =
|
|
152
|
+
route = '/' + cleanPrefixStr + route;
|
|
153
153
|
}
|
|
154
154
|
// Remove trailing slash unless it's the root
|
|
155
|
-
if (route !==
|
|
155
|
+
if (route !== '/' && route.endsWith('/')) {
|
|
156
156
|
route = route.slice(0, -1);
|
|
157
157
|
}
|
|
158
158
|
return route;
|
|
@@ -187,8 +187,8 @@ export class ApiRouter {
|
|
|
187
187
|
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
188
188
|
*/
|
|
189
189
|
matchRoute(requestPath, routePath) {
|
|
190
|
-
const reqSegments = requestPath.split(
|
|
191
|
-
const routeSegments = routePath.split(
|
|
190
|
+
const reqSegments = requestPath.split('/').filter(Boolean);
|
|
191
|
+
const routeSegments = routePath.split('/').filter(Boolean);
|
|
192
192
|
if (reqSegments.length !== routeSegments.length) {
|
|
193
193
|
return null;
|
|
194
194
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ApiRouter } from
|
|
2
|
-
import type { ServerOptions } from
|
|
1
|
+
import type { ApiRouter } from './api-router.js';
|
|
2
|
+
import type { ServerOptions } from '../types/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* Generates an OpenAPI 3.0 document from the router's routes and global options.
|
|
5
5
|
* @param router The router instance with loaded routes.
|
package/dist/src/core/openapi.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { zodToJsonSchema } from
|
|
1
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
2
2
|
/**
|
|
3
3
|
* Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
|
|
4
4
|
* For each property in the Zod schema, an OpenAPI parameter is constructed
|
|
@@ -12,14 +12,14 @@ function buildParameters(zodSchema, location) {
|
|
|
12
12
|
const parameters = [];
|
|
13
13
|
if (zodSchema &&
|
|
14
14
|
zodSchema._def &&
|
|
15
|
-
typeof zodSchema._def.shape ===
|
|
15
|
+
typeof zodSchema._def.shape === 'function') {
|
|
16
16
|
// Get the shape of the Zod schema
|
|
17
17
|
const shape = zodSchema._def.shape();
|
|
18
18
|
for (const key in shape) {
|
|
19
19
|
// Get the definition of the field
|
|
20
20
|
const fieldDef = shape[key];
|
|
21
21
|
// Determine if the field is optional
|
|
22
|
-
const isOptional = fieldDef._def.typeName ===
|
|
22
|
+
const isOptional = fieldDef._def.typeName === 'ZodOptional';
|
|
23
23
|
parameters.push({
|
|
24
24
|
// Set the name of the parameter
|
|
25
25
|
name: key,
|
|
@@ -28,7 +28,7 @@ function buildParameters(zodSchema, location) {
|
|
|
28
28
|
// Set the required flag
|
|
29
29
|
required: !isOptional,
|
|
30
30
|
// Set the schema type
|
|
31
|
-
schema: { type:
|
|
31
|
+
schema: { type: 'string' },
|
|
32
32
|
// Description of the parameter
|
|
33
33
|
description: `${location} parameter ${key}`,
|
|
34
34
|
});
|
|
@@ -49,11 +49,11 @@ function buildRequestBody(zodSchema) {
|
|
|
49
49
|
const jsonSchema = zodToJsonSchema(zodSchema);
|
|
50
50
|
return {
|
|
51
51
|
content: {
|
|
52
|
-
|
|
52
|
+
'application/json': {
|
|
53
53
|
schema: jsonSchema,
|
|
54
54
|
},
|
|
55
55
|
},
|
|
56
|
-
description:
|
|
56
|
+
description: 'Request body',
|
|
57
57
|
required: true,
|
|
58
58
|
};
|
|
59
59
|
}
|
|
@@ -65,7 +65,7 @@ function buildRequestBody(zodSchema) {
|
|
|
65
65
|
*/
|
|
66
66
|
function convertPathForOpenAPI(routePath) {
|
|
67
67
|
// Replace occurrences of :param with {param}
|
|
68
|
-
return routePath.replace(/:([a-zA-Z0-9_]+)/g,
|
|
68
|
+
return routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
71
71
|
* Generates an OpenAPI 3.0 document from the router's routes and global options.
|
|
@@ -75,11 +75,11 @@ function convertPathForOpenAPI(routePath) {
|
|
|
75
75
|
*/
|
|
76
76
|
export function generateOpenAPIDocument(router, options) {
|
|
77
77
|
const openapiDoc = {
|
|
78
|
-
openapi:
|
|
78
|
+
openapi: '3.0.0',
|
|
79
79
|
info: {
|
|
80
|
-
title: options.title ||
|
|
81
|
-
description: options.description ||
|
|
82
|
-
version: options.version ||
|
|
80
|
+
title: options.title || 'Burger API',
|
|
81
|
+
description: options.description || 'Burger API documentation',
|
|
82
|
+
version: options.version || '1.0.0',
|
|
83
83
|
},
|
|
84
84
|
paths: {},
|
|
85
85
|
};
|
|
@@ -97,14 +97,14 @@ export function generateOpenAPIDocument(router, options) {
|
|
|
97
97
|
const methodMeta = route.openapi?.[lowerMethod] || {};
|
|
98
98
|
// Generate an operationId: e.g., "get_api_product"
|
|
99
99
|
const operationId = methodMeta.operationId ||
|
|
100
|
-
`${lowerMethod}_${route.path.replace(/[\/:]/g,
|
|
100
|
+
`${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
|
|
101
101
|
// Build parameters for both path and query from the schema.
|
|
102
102
|
let parameters = [];
|
|
103
103
|
if (route.schema && route.schema[lowerMethod]) {
|
|
104
104
|
const schemaDef = route.schema[lowerMethod];
|
|
105
105
|
parameters = [
|
|
106
|
-
...buildParameters(schemaDef.params,
|
|
107
|
-
...buildParameters(schemaDef.query,
|
|
106
|
+
...buildParameters(schemaDef.params, 'path'),
|
|
107
|
+
...buildParameters(schemaDef.query, 'query'),
|
|
108
108
|
];
|
|
109
109
|
}
|
|
110
110
|
// Build requestBody if a body schema exists.
|
|
@@ -115,14 +115,14 @@ export function generateOpenAPIDocument(router, options) {
|
|
|
115
115
|
openapiDoc.paths[openApiPath][lowerMethod] = {
|
|
116
116
|
operationId,
|
|
117
117
|
summary: methodMeta.summary || `Summary for ${method} ${route.path}`,
|
|
118
|
-
description: methodMeta.description ||
|
|
118
|
+
description: methodMeta.description || '',
|
|
119
119
|
tags: methodMeta.tags || [],
|
|
120
120
|
deprecated: methodMeta.deprecated || false,
|
|
121
121
|
parameters: parameters,
|
|
122
122
|
requestBody: requestBody,
|
|
123
123
|
responses: methodMeta.responses || {
|
|
124
|
-
|
|
125
|
-
description:
|
|
124
|
+
'200': {
|
|
125
|
+
description: 'Successful response',
|
|
126
126
|
},
|
|
127
127
|
},
|
|
128
128
|
externalDocs: methodMeta.externalDocs || undefined,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PageDefinition } from
|
|
1
|
+
import type { PageDefinition } from '../types/index.js';
|
|
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,8 +1,8 @@
|
|
|
1
1
|
// Import stuff from node
|
|
2
|
-
import { readdirSync } from
|
|
3
|
-
import * as path from
|
|
2
|
+
import { readdirSync } from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from
|
|
5
|
+
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* PageRouter class for handling file-based page routing.
|
|
8
8
|
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
|
@@ -18,11 +18,11 @@ export class PageRouter {
|
|
|
18
18
|
* @param pagesDir The directory path where page modules are located.
|
|
19
19
|
* @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
|
|
20
20
|
*/
|
|
21
|
-
constructor(pagesDir, prefix =
|
|
21
|
+
constructor(pagesDir, prefix = '') {
|
|
22
22
|
this.pagesDir = pagesDir;
|
|
23
23
|
this.prefix = prefix;
|
|
24
24
|
if (!pagesDir) {
|
|
25
|
-
throw new Error(
|
|
25
|
+
throw new Error('Pages directory path must be provided');
|
|
26
26
|
}
|
|
27
27
|
// Normalize the pagesDir path
|
|
28
28
|
this.pagesDir = path.normalize(pagesDir);
|
|
@@ -45,7 +45,7 @@ export class PageRouter {
|
|
|
45
45
|
this.pages.sort((a, b) => compareRoutes(a, b));
|
|
46
46
|
}
|
|
47
47
|
catch (error) {
|
|
48
|
-
console.error(
|
|
48
|
+
console.error('Failed to load pages:', error);
|
|
49
49
|
throw new Error(`Failed to load pages: ${error instanceof Error ? error.message : String(error)}`);
|
|
50
50
|
}
|
|
51
51
|
}
|
|
@@ -54,7 +54,7 @@ export class PageRouter {
|
|
|
54
54
|
* @param dir The current directory to scan.
|
|
55
55
|
* @param basePath The base path for constructing the route path.
|
|
56
56
|
*/
|
|
57
|
-
async scanDirectory(dir, basePath =
|
|
57
|
+
async scanDirectory(dir, basePath = '') {
|
|
58
58
|
// Track if a dynamic folder has been found at this directory level
|
|
59
59
|
let dynamicFolderFound = false;
|
|
60
60
|
try {
|
|
@@ -85,13 +85,13 @@ export class PageRouter {
|
|
|
85
85
|
// Import the module
|
|
86
86
|
const pageModule = await import(modulePath);
|
|
87
87
|
// Get the default export as the page handler
|
|
88
|
-
if (entry.name.endsWith(
|
|
89
|
-
typeof pageModule.default !==
|
|
88
|
+
if (entry.name.endsWith('.tsx') &&
|
|
89
|
+
typeof pageModule.default !== 'function') {
|
|
90
90
|
throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
|
|
91
91
|
}
|
|
92
92
|
// Create page definition
|
|
93
93
|
const pageDefWithSlash = {
|
|
94
|
-
path: cleanedRoutePath +
|
|
94
|
+
path: cleanedRoutePath + '/',
|
|
95
95
|
handler: pageModule.default,
|
|
96
96
|
middleware: pageModule.middleware,
|
|
97
97
|
};
|
|
@@ -143,14 +143,14 @@ export class PageRouter {
|
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
145
|
// Construct the route with leading slash
|
|
146
|
-
let route =
|
|
146
|
+
let route = '/' + resultSegments.join('/');
|
|
147
147
|
// Apply prefix if provided
|
|
148
148
|
if (this.prefix) {
|
|
149
149
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
150
|
-
route =
|
|
150
|
+
route = '/' + cleanPrefixStr + route;
|
|
151
151
|
}
|
|
152
152
|
// Remove trailing slash unless it's the root
|
|
153
|
-
if (route !==
|
|
153
|
+
if (route !== '/' && route.endsWith('/')) {
|
|
154
154
|
route = route.slice(0, -1);
|
|
155
155
|
}
|
|
156
156
|
return route;
|
|
@@ -162,7 +162,7 @@ export class PageRouter {
|
|
|
162
162
|
*/
|
|
163
163
|
cleanRoutePath(routePath) {
|
|
164
164
|
// Break the route path into segments
|
|
165
|
-
const pathSegments = routePath.split(
|
|
165
|
+
const pathSegments = routePath.split('/');
|
|
166
166
|
// Get the last segment
|
|
167
167
|
if (pathSegments.length > 0) {
|
|
168
168
|
const lastSegment = pathSegments[pathSegments.length - 1];
|
|
@@ -173,14 +173,15 @@ export class PageRouter {
|
|
|
173
173
|
}
|
|
174
174
|
else {
|
|
175
175
|
// Remove file extension for non-index files
|
|
176
|
-
const extensionIndex = lastSegment.lastIndexOf(
|
|
176
|
+
const extensionIndex = lastSegment.lastIndexOf('.');
|
|
177
177
|
if (extensionIndex > 0) {
|
|
178
|
-
pathSegments[pathSegments.length - 1] =
|
|
178
|
+
pathSegments[pathSegments.length - 1] =
|
|
179
|
+
lastSegment.substring(0, extensionIndex);
|
|
179
180
|
}
|
|
180
181
|
}
|
|
181
182
|
}
|
|
182
183
|
// Join the segments back together
|
|
183
|
-
const finalPath = pathSegments.join(
|
|
184
|
+
const finalPath = pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
|
|
184
185
|
return finalPath;
|
|
185
186
|
}
|
|
186
187
|
/**
|
|
@@ -209,8 +210,8 @@ export class PageRouter {
|
|
|
209
210
|
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
210
211
|
*/
|
|
211
212
|
matchRoute(requestPath, pagePath) {
|
|
212
|
-
const reqSegments = requestPath.split(
|
|
213
|
-
const pageSegments = pagePath.split(
|
|
213
|
+
const reqSegments = requestPath.split('/').filter(Boolean);
|
|
214
|
+
const pageSegments = pagePath.split('/').filter(Boolean);
|
|
214
215
|
if (reqSegments.length !== pageSegments.length) {
|
|
215
216
|
return null;
|
|
216
217
|
}
|
|
@@ -58,7 +58,7 @@ export class HttpResponse {
|
|
|
58
58
|
* @returns The finalized Response object after building.
|
|
59
59
|
*/
|
|
60
60
|
json(data) {
|
|
61
|
-
this.header(
|
|
61
|
+
this.header('Content-Type', 'application/json');
|
|
62
62
|
this._body = JSON.stringify(data);
|
|
63
63
|
return this.build();
|
|
64
64
|
}
|
|
@@ -69,7 +69,7 @@ export class HttpResponse {
|
|
|
69
69
|
* @returns The finalized Response object after building.
|
|
70
70
|
*/
|
|
71
71
|
text(data) {
|
|
72
|
-
this.header(
|
|
72
|
+
this.header('Content-Type', 'text/plain');
|
|
73
73
|
this._body = data;
|
|
74
74
|
return this.build();
|
|
75
75
|
}
|
|
@@ -80,7 +80,7 @@ export class HttpResponse {
|
|
|
80
80
|
* @returns The finalized Response object after building.
|
|
81
81
|
*/
|
|
82
82
|
html(data) {
|
|
83
|
-
this.header(
|
|
83
|
+
this.header('Content-Type', 'text/html');
|
|
84
84
|
this._body = data;
|
|
85
85
|
return this.build();
|
|
86
86
|
}
|
|
@@ -92,7 +92,7 @@ export class HttpResponse {
|
|
|
92
92
|
*/
|
|
93
93
|
redirect(url, status = 302) {
|
|
94
94
|
this.status(status);
|
|
95
|
-
this.header(
|
|
95
|
+
this.header('Location', url);
|
|
96
96
|
this._body = null;
|
|
97
97
|
return this;
|
|
98
98
|
}
|
|
@@ -111,9 +111,9 @@ export class HttpResponse {
|
|
|
111
111
|
return this.build();
|
|
112
112
|
}
|
|
113
113
|
catch (error) {
|
|
114
|
-
console.error(
|
|
114
|
+
console.error('Error serving file:', error);
|
|
115
115
|
this.status(404);
|
|
116
|
-
this._body =
|
|
116
|
+
this._body = 'File not found';
|
|
117
117
|
return this.build();
|
|
118
118
|
}
|
|
119
119
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServerOptions, RequestHandler } from
|
|
1
|
+
import type { ServerOptions, RequestHandler } from '../types/index.js';
|
|
2
2
|
export declare class Server {
|
|
3
3
|
private options;
|
|
4
4
|
private server;
|
|
@@ -14,7 +14,9 @@ export declare class Server {
|
|
|
14
14
|
* @param port - The port to listen on.
|
|
15
15
|
* @param cb - An optional callback function to be called when the server starts.
|
|
16
16
|
*/
|
|
17
|
-
start(routes:
|
|
17
|
+
start(routes: {
|
|
18
|
+
[key: string]: any;
|
|
19
|
+
} | undefined, handler: RequestHandler, port: number, cb?: () => void): void;
|
|
18
20
|
/**
|
|
19
21
|
* Stops the server.
|
|
20
22
|
* If the server is currently running, this method will stop the server and
|
package/dist/src/core/server.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
// Import stuff from Bun
|
|
2
|
+
import { serve } from 'bun';
|
|
1
3
|
// Import stuff from core
|
|
2
|
-
import { HttpRequest } from
|
|
3
|
-
import { HttpResponse } from
|
|
4
|
+
import { HttpRequest } from './request.js';
|
|
5
|
+
import { HttpResponse } from './response.js';
|
|
4
6
|
// Import stuff from utils
|
|
5
|
-
import { errorResponse } from
|
|
7
|
+
import { errorResponse } from '../utils/error.js';
|
|
6
8
|
export class Server {
|
|
7
9
|
options;
|
|
8
10
|
server = null;
|
|
@@ -22,8 +24,9 @@ export class Server {
|
|
|
22
24
|
*/
|
|
23
25
|
start(routes, handler, port, cb) {
|
|
24
26
|
// Start Bun's native server using Bun.serve
|
|
25
|
-
this.server =
|
|
27
|
+
this.server = serve({
|
|
26
28
|
routes,
|
|
29
|
+
// Burger's fetch handler
|
|
27
30
|
fetch: async (request) => {
|
|
28
31
|
try {
|
|
29
32
|
// Wrap the native Request with HttpRequest to get a BurgerRequest
|
|
@@ -56,7 +59,7 @@ export class Server {
|
|
|
56
59
|
stop() {
|
|
57
60
|
if (this.server) {
|
|
58
61
|
this.server.stop();
|
|
59
|
-
console.log(
|
|
62
|
+
console.log('Server stopped.');
|
|
60
63
|
}
|
|
61
64
|
}
|
|
62
65
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServerOptions, Middleware } from
|
|
1
|
+
import type { ServerOptions, Middleware } from './types/index.js';
|
|
2
2
|
export declare class Burger {
|
|
3
3
|
private options;
|
|
4
4
|
private server;
|
|
@@ -28,5 +28,5 @@ export declare class Burger {
|
|
|
28
28
|
*/
|
|
29
29
|
serve(port?: number, cb?: () => void): Promise<void>;
|
|
30
30
|
}
|
|
31
|
-
export { setDir } from
|
|
32
|
-
export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, Middleware, openapi, } from
|
|
31
|
+
export { setDir } from './utils/index.js';
|
|
32
|
+
export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, BurgerNext, Middleware, openapi, } from './types/index.js';
|
package/dist/src/index.js
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
// Import stuff from core
|
|
2
|
-
import { Server } from
|
|
3
|
-
import { ApiRouter } from
|
|
4
|
-
import { PageRouter } from
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { generateOpenAPIDocument } from "./core/openapi.js";
|
|
8
|
-
import { swaggerHtml } from "./core/swagger-ui.js";
|
|
2
|
+
import { Server } from './core/server.js';
|
|
3
|
+
import { ApiRouter } from './core/api-router.js';
|
|
4
|
+
import { PageRouter } from './core/page-router.js';
|
|
5
|
+
import { generateOpenAPIDocument } from './core/openapi.js';
|
|
6
|
+
import { swaggerHtml } from './core/swagger-ui.js';
|
|
9
7
|
// Import middleware
|
|
10
|
-
import { createValidationMiddleware } from
|
|
8
|
+
import { createValidationMiddleware } from './middleware/validator.js';
|
|
11
9
|
export class Burger {
|
|
12
10
|
options;
|
|
13
11
|
server;
|
|
@@ -28,11 +26,11 @@ export class Burger {
|
|
|
28
26
|
this.server = new Server(options);
|
|
29
27
|
// Initialize API router
|
|
30
28
|
if (options.apiDir) {
|
|
31
|
-
this.apiRouter = new ApiRouter(options.apiDir,
|
|
29
|
+
this.apiRouter = new ApiRouter(options.apiDir, 'api');
|
|
32
30
|
}
|
|
33
31
|
// Initialize page router
|
|
34
32
|
if (options.pageDir) {
|
|
35
|
-
this.pageRouter = new PageRouter(options.pageDir,
|
|
33
|
+
this.pageRouter = new PageRouter(options.pageDir, '');
|
|
36
34
|
}
|
|
37
35
|
// Add global middleware
|
|
38
36
|
if (options.globalMiddleware) {
|
|
@@ -55,57 +53,64 @@ export class Burger {
|
|
|
55
53
|
async serve(port = 4000, cb) {
|
|
56
54
|
// File-based routing mode
|
|
57
55
|
const routes = {};
|
|
58
|
-
//
|
|
56
|
+
// Handle page routes
|
|
59
57
|
if (this.pageRouter) {
|
|
58
|
+
// Load Page routes
|
|
60
59
|
await this.pageRouter.loadPages();
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
60
|
+
// If there are any page routes, add them to the routes object
|
|
61
|
+
if (this.pageRouter.pages.length > 0) {
|
|
62
|
+
this.pageRouter.pages.forEach((page) => {
|
|
63
|
+
routes[page.path] = page.handler;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
64
66
|
}
|
|
65
67
|
if (this.apiRouter) {
|
|
66
68
|
// Load API routes
|
|
67
69
|
await this.apiRouter.loadRoutes();
|
|
68
70
|
// Start the server
|
|
69
|
-
this.server.start(routes, async (req) => {
|
|
70
|
-
// Wrap the native request with helper methods
|
|
71
|
-
const request = new HttpRequest(req);
|
|
72
|
-
// Create a new instance of BurgerResponse for the handler
|
|
73
|
-
const response = new HttpResponse();
|
|
71
|
+
this.server.start(routes, async (req, res) => {
|
|
74
72
|
// Create URL object
|
|
75
|
-
const url = new URL(
|
|
73
|
+
const url = new URL(req.url);
|
|
76
74
|
// Check if the request is for /openapi.json
|
|
77
|
-
if (url.pathname ===
|
|
75
|
+
if (url.pathname === '/openapi.json') {
|
|
78
76
|
if (this.apiRouter) {
|
|
79
77
|
// Generate OpenAPI document
|
|
80
78
|
const doc = generateOpenAPIDocument(this.apiRouter, this.options);
|
|
81
79
|
// Return it as JSON
|
|
82
|
-
return
|
|
80
|
+
return res.json(doc);
|
|
83
81
|
}
|
|
84
82
|
else {
|
|
85
|
-
// Return
|
|
86
|
-
return
|
|
83
|
+
// Return a descriptive error if router is not available
|
|
84
|
+
return res
|
|
87
85
|
.status(500)
|
|
88
|
-
.json({
|
|
86
|
+
.json({
|
|
87
|
+
error: 'API Router not configured',
|
|
88
|
+
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.'
|
|
89
|
+
});
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
// Serve the Swagger UI at /docs
|
|
92
|
-
if (url.pathname ===
|
|
93
|
-
return
|
|
93
|
+
if (url.pathname === '/docs') {
|
|
94
|
+
return res.html(swaggerHtml);
|
|
94
95
|
}
|
|
95
96
|
// Get the route and params for the current request
|
|
96
97
|
const { route, params } = this.apiRouter.resolve(req);
|
|
97
98
|
if (!route) {
|
|
98
99
|
// Return a 404 if no route is found
|
|
99
|
-
return
|
|
100
|
+
return res
|
|
101
|
+
.status(404)
|
|
102
|
+
.json({ error: 'Route not found' });
|
|
100
103
|
}
|
|
101
104
|
// Add params to the request
|
|
102
|
-
|
|
105
|
+
req.params = params;
|
|
103
106
|
// Get the handler for the current HTTP method
|
|
104
107
|
const method = req.method.toUpperCase();
|
|
105
108
|
const handler = route.handlers[method];
|
|
106
109
|
if (!handler) {
|
|
107
110
|
// Return a 405 if no handler is found
|
|
108
|
-
return
|
|
111
|
+
return res
|
|
112
|
+
.status(405)
|
|
113
|
+
.json({ error: 'Method Not Allowed' });
|
|
109
114
|
}
|
|
110
115
|
/**
|
|
111
116
|
* Build the middleware composition chain.
|
|
@@ -115,26 +120,28 @@ export class Burger {
|
|
|
115
120
|
* 4. Execute the handler
|
|
116
121
|
*/
|
|
117
122
|
// 1. Compose the Route-Specific Chain
|
|
118
|
-
let routeChain = async () => handler(
|
|
123
|
+
let routeChain = async () => handler(req, res);
|
|
119
124
|
if (route.middleware && route.middleware.length > 0) {
|
|
120
125
|
// Wrap route-specific middleware (in reverse order to preserve order of execution)
|
|
121
126
|
for (const mw of route.middleware.slice().reverse()) {
|
|
122
127
|
const next = routeChain;
|
|
123
|
-
routeChain = async () => mw(
|
|
128
|
+
routeChain = async () => mw(req, res, next);
|
|
124
129
|
}
|
|
125
130
|
}
|
|
126
131
|
// 2. Insert Validation Middleware (if a schema exists)
|
|
127
132
|
let composedChain = routeChain;
|
|
128
133
|
if (route.schema) {
|
|
129
134
|
const validationMw = createValidationMiddleware(route.schema);
|
|
130
|
-
composedChain = async () => validationMw(
|
|
135
|
+
composedChain = async () => validationMw(req, res, routeChain);
|
|
131
136
|
}
|
|
132
137
|
// 3. Wrap Global Middleware (in reverse order so that the first-added runs first)
|
|
133
138
|
let finalHandler = composedChain;
|
|
134
139
|
if (this.globalMiddleware.length > 0) {
|
|
135
|
-
for (const mw of this.globalMiddleware
|
|
140
|
+
for (const mw of this.globalMiddleware
|
|
141
|
+
.slice()
|
|
142
|
+
.reverse()) {
|
|
136
143
|
const next = finalHandler;
|
|
137
|
-
finalHandler = async () => mw(
|
|
144
|
+
finalHandler = async () => mw(req, res, next);
|
|
138
145
|
}
|
|
139
146
|
}
|
|
140
147
|
// Execute the full chain
|
|
@@ -143,11 +150,13 @@ export class Burger {
|
|
|
143
150
|
}
|
|
144
151
|
else {
|
|
145
152
|
// Fallback to default handler if no router is provided
|
|
146
|
-
this.server.start(
|
|
147
|
-
|
|
148
|
-
|
|
153
|
+
this.server.start(undefined, async (_, res) => {
|
|
154
|
+
return res
|
|
155
|
+
.status(200)
|
|
156
|
+
.json({ message: 'Hello from burger-api!' });
|
|
157
|
+
}, port, cb);
|
|
149
158
|
}
|
|
150
159
|
}
|
|
151
160
|
}
|
|
152
161
|
// Export utils
|
|
153
|
-
export { setDir } from
|
|
162
|
+
export { setDir } from './utils/index.js';
|