@macss/modular-api 0.4.5 → 0.4.6
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/dist/core/body_parser_error_handler.d.ts +15 -0
- package/dist/core/body_parser_error_handler.js +35 -0
- package/dist/core/modular_api.d.ts +9 -0
- package/dist/core/modular_api.js +9 -2
- package/dist/core/schema/field.d.ts +2 -1
- package/dist/core/schema/field.js +4 -0
- package/dist/core/usecase.js +1 -0
- package/dist/core/usecase_handler.js +3 -2
- package/dist/openapi/swagger_docs.d.ts +7 -6
- package/dist/openapi/swagger_docs.js +12 -193
- package/package.json +4 -3
- package/dist/core/usecase_test_handler.d.ts +0 -27
- package/dist/core/usecase_test_handler.js +0 -60
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from 'express';
|
|
2
|
+
/**
|
|
3
|
+
* Express error-handling middleware for body-parser SyntaxErrors.
|
|
4
|
+
*
|
|
5
|
+
* When `express.json()` encounters malformed JSON, it calls `next(err)`
|
|
6
|
+
* with a `SyntaxError` whose `type` is `'entity.parse.failed'`.
|
|
7
|
+
* This handler intercepts that specific error, logs it through the
|
|
8
|
+
* request-scoped logger (so it carries `trace_id`), and returns a
|
|
9
|
+
* structured 400 response.
|
|
10
|
+
*
|
|
11
|
+
* Any other error is forwarded to the next error handler via `next(err)`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function bodyParserErrorHandler(err: SyntaxError & {
|
|
14
|
+
type?: string;
|
|
15
|
+
}, req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================
|
|
3
|
+
// core/body_parser_error_handler.ts
|
|
4
|
+
// Express error middleware — catches SyntaxError from
|
|
5
|
+
// express.json() (body-parser) and returns a structured 400
|
|
6
|
+
// with scoped-logger warning (trace_id preserved).
|
|
7
|
+
//
|
|
8
|
+
// Must be mounted immediately after express.json() in serve().
|
|
9
|
+
// ============================================================
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.bodyParserErrorHandler = bodyParserErrorHandler;
|
|
12
|
+
const logging_middleware_1 = require("./logger/logging_middleware");
|
|
13
|
+
/**
|
|
14
|
+
* Express error-handling middleware for body-parser SyntaxErrors.
|
|
15
|
+
*
|
|
16
|
+
* When `express.json()` encounters malformed JSON, it calls `next(err)`
|
|
17
|
+
* with a `SyntaxError` whose `type` is `'entity.parse.failed'`.
|
|
18
|
+
* This handler intercepts that specific error, logs it through the
|
|
19
|
+
* request-scoped logger (so it carries `trace_id`), and returns a
|
|
20
|
+
* structured 400 response.
|
|
21
|
+
*
|
|
22
|
+
* Any other error is forwarded to the next error handler via `next(err)`.
|
|
23
|
+
*/
|
|
24
|
+
function bodyParserErrorHandler(err, req, res, next) {
|
|
25
|
+
if (err instanceof SyntaxError && err.type === 'entity.parse.failed') {
|
|
26
|
+
const logger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
|
|
27
|
+
logger?.warning('Invalid JSON in request body', {
|
|
28
|
+
error: err.message,
|
|
29
|
+
status: 400,
|
|
30
|
+
});
|
|
31
|
+
res.status(400).json({ error: 'Invalid JSON in request body' });
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
next(err);
|
|
35
|
+
}
|
|
@@ -26,6 +26,14 @@ export interface ModularApiOptions {
|
|
|
26
26
|
* Default: LogLevel.info (emits emergency..info, suppresses debug).
|
|
27
27
|
*/
|
|
28
28
|
logLevel?: LogLevel;
|
|
29
|
+
/**
|
|
30
|
+
* OpenAPI `servers` list. Each entry has a `url` and optional `description`.
|
|
31
|
+
* When omitted, `serve()` generates `[{url: 'http://localhost:{port}'}]`.
|
|
32
|
+
*/
|
|
33
|
+
servers?: Array<{
|
|
34
|
+
url: string;
|
|
35
|
+
description?: string;
|
|
36
|
+
}>;
|
|
29
37
|
}
|
|
30
38
|
/**
|
|
31
39
|
* Main entry point for modular_api.
|
|
@@ -64,6 +72,7 @@ export declare class ModularApi {
|
|
|
64
72
|
private readonly httpRequestsInFlight?;
|
|
65
73
|
private readonly httpRequestDuration?;
|
|
66
74
|
private readonly logLevel;
|
|
75
|
+
private readonly servers?;
|
|
67
76
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
68
77
|
get metrics(): MetricsRegistrar | undefined;
|
|
69
78
|
constructor(options?: ModularApiOptions);
|
package/dist/core/modular_api.js
CHANGED
|
@@ -19,6 +19,7 @@ const metric_registry_1 = require("./metrics/metric_registry");
|
|
|
19
19
|
const metrics_middleware_1 = require("./metrics/metrics_middleware");
|
|
20
20
|
const logging_middleware_1 = require("./logger/logging_middleware");
|
|
21
21
|
const logger_1 = require("./logger/logger");
|
|
22
|
+
const body_parser_error_handler_1 = require("./body_parser_error_handler");
|
|
22
23
|
const registry_1 = require("./registry");
|
|
23
24
|
/**
|
|
24
25
|
* Main entry point for modular_api.
|
|
@@ -59,6 +60,8 @@ class ModularApi {
|
|
|
59
60
|
httpRequestDuration;
|
|
60
61
|
// Logging
|
|
61
62
|
logLevel;
|
|
63
|
+
// OpenAPI
|
|
64
|
+
servers;
|
|
62
65
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
63
66
|
get metrics() {
|
|
64
67
|
return this._metricsRegistrar;
|
|
@@ -76,6 +79,8 @@ class ModularApi {
|
|
|
76
79
|
this.excludedMetricsRoutes = options.excludedMetricsRoutes ?? ['/metrics', '/health', '/docs'];
|
|
77
80
|
// Logging
|
|
78
81
|
this.logLevel = options.logLevel ?? logger_1.LogLevel.info;
|
|
82
|
+
// OpenAPI servers
|
|
83
|
+
this.servers = options.servers;
|
|
79
84
|
if (this.metricsEnabled) {
|
|
80
85
|
this.metricRegistry = new metric_registry_1.MetricRegistry();
|
|
81
86
|
this._metricsRegistrar = new metric_registry_1.MetricsRegistrar(this.metricRegistry);
|
|
@@ -95,7 +100,6 @@ class ModularApi {
|
|
|
95
100
|
});
|
|
96
101
|
}
|
|
97
102
|
this.app = (0, express_1.default)();
|
|
98
|
-
this.app.use(express_1.default.json());
|
|
99
103
|
this.rootRouter = express_1.default.Router();
|
|
100
104
|
}
|
|
101
105
|
/**
|
|
@@ -161,6 +165,9 @@ class ModularApi {
|
|
|
161
165
|
serviceName: this.title,
|
|
162
166
|
excludedRoutes: excludedLogRoutes,
|
|
163
167
|
}));
|
|
168
|
+
// Body parsing AFTER loggingMiddleware — SyntaxErrors now have trace_id.
|
|
169
|
+
this.app.use(express_1.default.json());
|
|
170
|
+
this.app.use(body_parser_error_handler_1.bodyParserErrorHandler);
|
|
164
171
|
// Metrics middleware — before user middlewares & routes.
|
|
165
172
|
// Created here so registeredPaths is populated from apiRegistry.
|
|
166
173
|
if (this.metricsEnabled &&
|
|
@@ -191,7 +198,7 @@ class ModularApi {
|
|
|
191
198
|
// Swagger UI docs — inline HTML, no external dependency (PRD-003).
|
|
192
199
|
this.app.get('/docs', (0, swagger_docs_1.swaggerDocsHandler)({ title: this.title }));
|
|
193
200
|
// Raw spec endpoints
|
|
194
|
-
const spec = (0, openapi_1.buildOpenApiSpec)({ title: this.title, port });
|
|
201
|
+
const spec = (0, openapi_1.buildOpenApiSpec)({ title: this.title, port, servers: this.servers });
|
|
195
202
|
this.app.get('/openapi.json', (0, openapi_1.openApiJsonHandler)(spec));
|
|
196
203
|
this.app.get('/openapi.yaml', (0, openapi_1.openApiYamlHandler)(spec));
|
|
197
204
|
const server = this.app.listen(port, host, () => {
|
|
@@ -6,7 +6,7 @@ declare global {
|
|
|
6
6
|
/** Metadata stored per decorated field. */
|
|
7
7
|
export interface FieldMeta {
|
|
8
8
|
name: string;
|
|
9
|
-
type: 'string' | 'integer' | 'number' | 'boolean' | 'array';
|
|
9
|
+
type: 'string' | 'integer' | 'number' | 'boolean' | 'array' | 'object';
|
|
10
10
|
description?: string;
|
|
11
11
|
required: boolean;
|
|
12
12
|
nullable: boolean;
|
|
@@ -33,6 +33,7 @@ export declare const Field: {
|
|
|
33
33
|
integer(options?: FieldOptions): FieldDecorator & PendingField;
|
|
34
34
|
number(options?: FieldOptions): FieldDecorator & PendingField;
|
|
35
35
|
boolean(options?: FieldOptions): FieldDecorator & PendingField;
|
|
36
|
+
object(options?: FieldOptions): FieldDecorator & PendingField;
|
|
36
37
|
/**
|
|
37
38
|
* Marks a field as optional (nullable, not required).
|
|
38
39
|
*
|
|
@@ -60,6 +60,10 @@ exports.Field = {
|
|
|
60
60
|
const decorator = makeFieldDecorator('boolean', options);
|
|
61
61
|
return Object.assign(decorator, { __pending: true, type: 'boolean', options, extra: {} });
|
|
62
62
|
},
|
|
63
|
+
object(options = {}) {
|
|
64
|
+
const decorator = makeFieldDecorator('object', options);
|
|
65
|
+
return Object.assign(decorator, { __pending: true, type: 'object', options, extra: {} });
|
|
66
|
+
},
|
|
63
67
|
/**
|
|
64
68
|
* Marks a field as optional (nullable, not required).
|
|
65
69
|
*
|
package/dist/core/usecase.js
CHANGED
|
@@ -67,6 +67,7 @@ function isJsonTypeValid(value, expectedType) {
|
|
|
67
67
|
case 'number': return typeof value === 'number';
|
|
68
68
|
case 'boolean': return typeof value === 'boolean';
|
|
69
69
|
case 'array': return Array.isArray(value);
|
|
70
|
+
case 'object': return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
70
71
|
default: return true;
|
|
71
72
|
}
|
|
72
73
|
}
|
|
@@ -67,16 +67,17 @@ function useCaseHandler(factory, options = {}) {
|
|
|
67
67
|
res.status(output.statusCode).set(JSON_HEADERS).json(output.toJson());
|
|
68
68
|
}
|
|
69
69
|
catch (err) {
|
|
70
|
+
const logger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
|
|
70
71
|
if (err instanceof input_validation_error_1.InputValidationError) {
|
|
71
72
|
res.status(400).set(JSON_HEADERS).json({ error: err.message });
|
|
72
73
|
return;
|
|
73
74
|
}
|
|
74
75
|
if (err instanceof use_case_exception_1.UseCaseException) {
|
|
75
|
-
|
|
76
|
+
logger?.error('UseCaseException', { error: err.toString(), status: err.statusCode });
|
|
76
77
|
res.status(err.statusCode).set(JSON_HEADERS).json(err.toJson());
|
|
77
78
|
return;
|
|
78
79
|
}
|
|
79
|
-
|
|
80
|
+
logger?.error('Unexpected error in use case handler', { error: String(err) });
|
|
80
81
|
res.status(500).set(JSON_HEADERS).json({ error: 'Internal server error' });
|
|
81
82
|
}
|
|
82
83
|
};
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Docs UI handler — serves the `@macss/docs-ui` widget from CDN.
|
|
3
3
|
*
|
|
4
|
-
* Loads
|
|
5
|
-
* `/openapi.json` endpoint
|
|
6
|
-
*
|
|
4
|
+
* Loads `@macss/docs-ui` from jsdelivr CDN, which wraps Swagger UI with
|
|
5
|
+
* system-aware dark mode. The local `/openapi.json` endpoint provides
|
|
6
|
+
* the spec. Styling, dark mode, and Swagger UI loading are handled
|
|
7
|
+
* entirely by docs-ui — no inline CSS or JS in this template.
|
|
7
8
|
*
|
|
8
|
-
*
|
|
9
|
+
* See: https://github.com/macss-dev/modular_api/tree/main/code/docs-ui
|
|
9
10
|
*/
|
|
10
11
|
import type { RequestHandler } from 'express';
|
|
11
12
|
/**
|
|
12
|
-
* Returns an Express handler that serves the
|
|
13
|
+
* Returns an Express handler that serves the docs-ui HTML.
|
|
13
14
|
*
|
|
14
15
|
* Usage:
|
|
15
16
|
* ```ts
|
|
@@ -1,213 +1,32 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Docs UI handler — serves the `@macss/docs-ui` widget from CDN.
|
|
4
4
|
*
|
|
5
|
-
* Loads
|
|
6
|
-
* `/openapi.json` endpoint
|
|
7
|
-
*
|
|
5
|
+
* Loads `@macss/docs-ui` from jsdelivr CDN, which wraps Swagger UI with
|
|
6
|
+
* system-aware dark mode. The local `/openapi.json` endpoint provides
|
|
7
|
+
* the spec. Styling, dark mode, and Swagger UI loading are handled
|
|
8
|
+
* entirely by docs-ui — no inline CSS or JS in this template.
|
|
8
9
|
*
|
|
9
|
-
*
|
|
10
|
+
* See: https://github.com/macss-dev/modular_api/tree/main/code/docs-ui
|
|
10
11
|
*/
|
|
11
12
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
13
|
exports.swaggerDocsHandler = swaggerDocsHandler;
|
|
13
|
-
const
|
|
14
|
+
const DOCS_UI_CDN = 'https://cdn.jsdelivr.net/npm/@macss/docs-ui@0.1/dist';
|
|
15
|
+
const DOCS_UI_HTML_TEMPLATE = `<!DOCTYPE html>
|
|
14
16
|
<html>
|
|
15
17
|
<head>
|
|
16
18
|
<title>{{title}} — API Reference</title>
|
|
17
19
|
<meta charset="utf-8" />
|
|
18
20
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
19
|
-
<link
|
|
20
|
-
rel="stylesheet"
|
|
21
|
-
href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css"
|
|
22
|
-
/>
|
|
23
|
-
<style>
|
|
24
|
-
/* ── Light mode baseline (Swagger UI default) ───────────── */
|
|
25
|
-
:root {
|
|
26
|
-
--bg-primary: #ffffff;
|
|
27
|
-
--bg-secondary: #f7f7f7;
|
|
28
|
-
--bg-block: #ffffff;
|
|
29
|
-
--border-color: #e8e8e8;
|
|
30
|
-
--text-primary: #3b4151;
|
|
31
|
-
--text-muted: #6b7280;
|
|
32
|
-
--input-bg: #ffffff;
|
|
33
|
-
--input-text: #3b4151;
|
|
34
|
-
--input-border: #d9d9d9;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/* ── Dark mode overrides ───────────────────────────── */
|
|
38
|
-
@media (prefers-color-scheme: dark) {
|
|
39
|
-
:root {
|
|
40
|
-
--bg-primary: #1a1a1a;
|
|
41
|
-
--bg-secondary: #222222;
|
|
42
|
-
--bg-block: #2a2a2a;
|
|
43
|
-
--border-color: #3a3a3a;
|
|
44
|
-
--text-primary: #e0e0e0;
|
|
45
|
-
--text-muted: #a0a0a0;
|
|
46
|
-
--input-bg: #2a2a2a;
|
|
47
|
-
--input-text: #e0e0e0;
|
|
48
|
-
--input-border: #444444;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
body {
|
|
52
|
-
background-color: var(--bg-primary);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/* ── General text ──────────────────────────────── */
|
|
56
|
-
.swagger-ui,
|
|
57
|
-
.swagger-ui .info .title,
|
|
58
|
-
.swagger-ui .info p,
|
|
59
|
-
.swagger-ui .info li,
|
|
60
|
-
.swagger-ui .info a,
|
|
61
|
-
.swagger-ui .opblock-tag,
|
|
62
|
-
.swagger-ui .opblock-tag small,
|
|
63
|
-
.swagger-ui table thead tr td,
|
|
64
|
-
.swagger-ui table thead tr th,
|
|
65
|
-
.swagger-ui .response-col_status,
|
|
66
|
-
.swagger-ui .response-col_description,
|
|
67
|
-
.swagger-ui .parameter__name,
|
|
68
|
-
.swagger-ui .parameter__type,
|
|
69
|
-
.swagger-ui .parameter__in,
|
|
70
|
-
.swagger-ui .tab li,
|
|
71
|
-
.swagger-ui .model-title,
|
|
72
|
-
.swagger-ui .model,
|
|
73
|
-
.swagger-ui .prop-type,
|
|
74
|
-
.swagger-ui .prop-format {
|
|
75
|
-
color: var(--text-primary);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/* ── Backgrounds ───────────────────────────────── */
|
|
79
|
-
.swagger-ui .wrapper,
|
|
80
|
-
.swagger-ui .scheme-container,
|
|
81
|
-
.swagger-ui section.models,
|
|
82
|
-
.swagger-ui section.models .model-container,
|
|
83
|
-
.swagger-ui .model-box {
|
|
84
|
-
background: var(--bg-secondary);
|
|
85
|
-
border-color: var(--border-color);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/* ── Operation blocks ────────────────────────────── */
|
|
89
|
-
.swagger-ui .opblock {
|
|
90
|
-
background: var(--bg-block);
|
|
91
|
-
border-color: var(--border-color);
|
|
92
|
-
box-shadow: none;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
.swagger-ui .opblock .opblock-summary {
|
|
96
|
-
background: var(--bg-block);
|
|
97
|
-
border-color: var(--border-color);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
.swagger-ui .opblock .opblock-section-header {
|
|
101
|
-
background: var(--bg-secondary);
|
|
102
|
-
border-color: var(--border-color);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
.swagger-ui .opblock .opblock-section-header h4 {
|
|
106
|
-
color: var(--text-primary);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/* HTTP method accent colors preserved in dark mode */
|
|
110
|
-
.swagger-ui .opblock.opblock-post { border-color: #49cc90; }
|
|
111
|
-
.swagger-ui .opblock.opblock-get { border-color: #61affe; }
|
|
112
|
-
.swagger-ui .opblock.opblock-put { border-color: #fca130; }
|
|
113
|
-
.swagger-ui .opblock.opblock-delete { border-color: #f93e3e; }
|
|
114
|
-
.swagger-ui .opblock.opblock-patch { border-color: #50e3c2; }
|
|
115
|
-
|
|
116
|
-
.swagger-ui .opblock.opblock-post .opblock-summary-method { background: #49cc90; }
|
|
117
|
-
.swagger-ui .opblock.opblock-get .opblock-summary-method { background: #61affe; }
|
|
118
|
-
.swagger-ui .opblock.opblock-put .opblock-summary-method { background: #fca130; }
|
|
119
|
-
.swagger-ui .opblock.opblock-delete .opblock-summary-method { background: #f93e3e; }
|
|
120
|
-
.swagger-ui .opblock.opblock-patch .opblock-summary-method { background: #50e3c2; }
|
|
121
|
-
|
|
122
|
-
/* ── Inputs and controls ─────────────────────────── */
|
|
123
|
-
.swagger-ui input[type=text],
|
|
124
|
-
.swagger-ui input[type=password],
|
|
125
|
-
.swagger-ui input[type=search],
|
|
126
|
-
.swagger-ui input[type=email],
|
|
127
|
-
.swagger-ui textarea,
|
|
128
|
-
.swagger-ui select {
|
|
129
|
-
background: var(--input-bg);
|
|
130
|
-
color: var(--input-text);
|
|
131
|
-
border-color: var(--input-border);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/* ── Buttons ───────────────────────────────────── */
|
|
135
|
-
.swagger-ui .btn {
|
|
136
|
-
background: var(--bg-block);
|
|
137
|
-
color: var(--text-primary);
|
|
138
|
-
border-color: var(--border-color);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
.swagger-ui .btn.execute {
|
|
142
|
-
background: #4a90e2;
|
|
143
|
-
color: #ffffff;
|
|
144
|
-
border-color: #4a90e2;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
.swagger-ui .btn.authorize {
|
|
148
|
-
color: #49cc90;
|
|
149
|
-
border-color: #49cc90;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/* ── Response area ─────────────────────────────── */
|
|
153
|
-
.swagger-ui .responses-inner,
|
|
154
|
-
.swagger-ui .response-col_description__inner {
|
|
155
|
-
background: var(--bg-secondary);
|
|
156
|
-
color: var(--text-primary);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
.swagger-ui .highlight-code,
|
|
160
|
-
.swagger-ui .microlight {
|
|
161
|
-
background: #111111 !important;
|
|
162
|
-
color: #e0e0e0 !important;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/* ── Topbar ────────────────────────────────────── */
|
|
166
|
-
.swagger-ui .topbar {
|
|
167
|
-
background-color: #111111;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/* ── Expand/collapse arrows ──────────────────────── */
|
|
171
|
-
.swagger-ui .expand-methods svg,
|
|
172
|
-
.swagger-ui .expand-operation svg {
|
|
173
|
-
fill: var(--text-muted);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/* ── Filter input ──────────────────────────────── */
|
|
177
|
-
.swagger-ui .filter .operation-filter-input {
|
|
178
|
-
background: var(--input-bg);
|
|
179
|
-
color: var(--input-text);
|
|
180
|
-
border-color: var(--input-border);
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/* ── Scrollbar (webkit) ──────────────────────────── */
|
|
184
|
-
::-webkit-scrollbar { width: 8px; height: 8px; }
|
|
185
|
-
::-webkit-scrollbar-track { background: var(--bg-primary); }
|
|
186
|
-
::-webkit-scrollbar-thumb { background: #444444; border-radius: 4px; }
|
|
187
|
-
::-webkit-scrollbar-thumb:hover { background: #555555; }
|
|
188
|
-
}
|
|
189
|
-
</style>
|
|
190
21
|
</head>
|
|
191
22
|
<body>
|
|
192
23
|
<div id="swagger-ui"></div>
|
|
193
|
-
<script src="
|
|
194
|
-
</script>
|
|
195
|
-
<script>
|
|
196
|
-
SwaggerUIBundle({
|
|
197
|
-
url: "/openapi.json",
|
|
198
|
-
dom_id: "#swagger-ui",
|
|
199
|
-
presets: [
|
|
200
|
-
SwaggerUIBundle.presets.apis,
|
|
201
|
-
SwaggerUIBundle.SwaggerUIStandalonePreset
|
|
202
|
-
],
|
|
203
|
-
layout: "BaseLayout",
|
|
204
|
-
deepLinking: true
|
|
205
|
-
})
|
|
206
|
-
</script>
|
|
24
|
+
<script src="${DOCS_UI_CDN}/docs-ui.js"></script>
|
|
25
|
+
<script>DocsUI.init({ specUrl: "/openapi.json" })</script>
|
|
207
26
|
</body>
|
|
208
27
|
</html>`;
|
|
209
28
|
/**
|
|
210
|
-
* Returns an Express handler that serves the
|
|
29
|
+
* Returns an Express handler that serves the docs-ui HTML.
|
|
211
30
|
*
|
|
212
31
|
* Usage:
|
|
213
32
|
* ```ts
|
|
@@ -215,7 +34,7 @@ const SWAGGER_UI_HTML_TEMPLATE = `<!DOCTYPE html>
|
|
|
215
34
|
* ```
|
|
216
35
|
*/
|
|
217
36
|
function swaggerDocsHandler(options) {
|
|
218
|
-
const html =
|
|
37
|
+
const html = DOCS_UI_HTML_TEMPLATE.replace('{{title}}', options.title);
|
|
219
38
|
return (_req, res) => {
|
|
220
39
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
221
40
|
res.send(html);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@macss/modular-api",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.6",
|
|
4
4
|
"description": "Use-case-centric toolkit for building modular APIs with Express. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose Swagger/OpenAPI documentation automatically.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
],
|
|
12
12
|
"scripts": {
|
|
13
13
|
"build": "tsc --project tsconfig.build.json",
|
|
14
|
+
"prepublishOnly": "npm run build",
|
|
14
15
|
"dev": "ts-node src/index.ts",
|
|
15
16
|
"test": "vitest run",
|
|
16
17
|
"format": "prettier --write .",
|
|
@@ -28,12 +29,12 @@
|
|
|
28
29
|
"repository": {
|
|
29
30
|
"type": "git",
|
|
30
31
|
"url": "https://github.com/macss-dev/modular_api.git",
|
|
31
|
-
"directory": "ts"
|
|
32
|
+
"directory": "code/ts"
|
|
32
33
|
},
|
|
33
34
|
"bugs": {
|
|
34
35
|
"url": "https://github.com/macss-dev/modular_api/issues"
|
|
35
36
|
},
|
|
36
|
-
"homepage": "https://github.com/macss-dev/modular_api/tree/main/ts#readme",
|
|
37
|
+
"homepage": "https://github.com/macss-dev/modular_api/tree/main/code/ts#readme",
|
|
37
38
|
"dependencies": {
|
|
38
39
|
"express": "^4.22.1"
|
|
39
40
|
},
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import type { UseCaseFactory, Input, Output } from './usecase';
|
|
2
|
-
import type { ModularLogger } from './logger/logger';
|
|
3
|
-
export interface TestResponse {
|
|
4
|
-
statusCode: number;
|
|
5
|
-
body: Record<string, unknown>;
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Executes a UseCase directly from a plain JSON object, without Express.
|
|
9
|
-
* Ideal for unit tests — no HTTP server needed.
|
|
10
|
-
*
|
|
11
|
-
* Mirrors the Dart `useCaseTestHandler` pattern.
|
|
12
|
-
*
|
|
13
|
-
* Returns a `TestResponse` with `statusCode` and `body` so you can assert
|
|
14
|
-
* on both the HTTP status and the JSON payload.
|
|
15
|
-
*
|
|
16
|
-
* Usage:
|
|
17
|
-
* ```ts
|
|
18
|
-
* import { useCaseTestHandler } from 'modular_api';
|
|
19
|
-
*
|
|
20
|
-
* const response = await useCaseTestHandler(SayHello.fromJson, { name: 'World' });
|
|
21
|
-
* expect(response.statusCode).toBe(200);
|
|
22
|
-
* expect(response.body).toEqual({ message: 'Hello, World!' });
|
|
23
|
-
* ```
|
|
24
|
-
*/
|
|
25
|
-
export declare function useCaseTestHandler<I extends Input, O extends Output>(factory: UseCaseFactory<I, O>, input?: Record<string, unknown>, options?: {
|
|
26
|
-
logger?: ModularLogger;
|
|
27
|
-
}): Promise<TestResponse>;
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// ============================================================
|
|
3
|
-
// core/usecase_test_handler.ts
|
|
4
|
-
// Test helper — runs a UseCase without an HTTP server.
|
|
5
|
-
// Mirror of useCaseTestHandler() in Dart.
|
|
6
|
-
// ============================================================
|
|
7
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
-
exports.useCaseTestHandler = useCaseTestHandler;
|
|
9
|
-
const use_case_exception_1 = require("./use_case_exception");
|
|
10
|
-
/**
|
|
11
|
-
* Executes a UseCase directly from a plain JSON object, without Express.
|
|
12
|
-
* Ideal for unit tests — no HTTP server needed.
|
|
13
|
-
*
|
|
14
|
-
* Mirrors the Dart `useCaseTestHandler` pattern.
|
|
15
|
-
*
|
|
16
|
-
* Returns a `TestResponse` with `statusCode` and `body` so you can assert
|
|
17
|
-
* on both the HTTP status and the JSON payload.
|
|
18
|
-
*
|
|
19
|
-
* Usage:
|
|
20
|
-
* ```ts
|
|
21
|
-
* import { useCaseTestHandler } from 'modular_api';
|
|
22
|
-
*
|
|
23
|
-
* const response = await useCaseTestHandler(SayHello.fromJson, { name: 'World' });
|
|
24
|
-
* expect(response.statusCode).toBe(200);
|
|
25
|
-
* expect(response.body).toEqual({ message: 'Hello, World!' });
|
|
26
|
-
* ```
|
|
27
|
-
*/
|
|
28
|
-
async function useCaseTestHandler(factory, input = {}, options) {
|
|
29
|
-
try {
|
|
30
|
-
const useCase = factory(input);
|
|
31
|
-
// Inject logger if provided
|
|
32
|
-
if (options?.logger) {
|
|
33
|
-
useCase.logger = options.logger;
|
|
34
|
-
}
|
|
35
|
-
const validationError = useCase.validate();
|
|
36
|
-
if (validationError !== null) {
|
|
37
|
-
return {
|
|
38
|
-
statusCode: 400,
|
|
39
|
-
body: { error: validationError },
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
await useCase.execute();
|
|
43
|
-
return {
|
|
44
|
-
statusCode: useCase.output.statusCode,
|
|
45
|
-
body: useCase.toJson(),
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
catch (err) {
|
|
49
|
-
if (err instanceof use_case_exception_1.UseCaseException) {
|
|
50
|
-
return {
|
|
51
|
-
statusCode: err.statusCode,
|
|
52
|
-
body: err.toJson(),
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
return {
|
|
56
|
-
statusCode: 500,
|
|
57
|
-
body: { error: 'Internal server error' },
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
}
|