@tahminator/sapling 2.0.5 → 2.1.0-beta.0e8a97e8
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 +161 -12
- package/dist/index.cjs +676 -299
- package/dist/index.d.cts +609 -85
- package/dist/index.d.mts +609 -85
- package/dist/index.mjs +636 -299
- package/package.json +8 -2
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import e, { Router } from "express";
|
|
2
|
+
import swagger from "swagger-ui-express";
|
|
2
3
|
//#region src/html/404.ts
|
|
3
4
|
/**
|
|
4
5
|
* Default Express.js 404 error page, as a string.
|
|
@@ -22,6 +23,7 @@ const Html404ErrorPage = (error) => `<!DOCTYPE html>
|
|
|
22
23
|
* You can either return `new RedirectView(url)` or `RedirectView.redirect(url)` inside of a controller method.
|
|
23
24
|
*/
|
|
24
25
|
var RedirectView = class RedirectView {
|
|
26
|
+
_url;
|
|
25
27
|
constructor(url) {
|
|
26
28
|
this._url = url;
|
|
27
29
|
}
|
|
@@ -117,8 +119,10 @@ let HttpStatus = /* @__PURE__ */ function(HttpStatus) {
|
|
|
117
119
|
* @typeParam T - the type of the response body
|
|
118
120
|
*/
|
|
119
121
|
var ResponseEntity = class {
|
|
122
|
+
_statusCode;
|
|
123
|
+
_headers = {};
|
|
124
|
+
_body;
|
|
120
125
|
constructor(body, headers = {}, statusCode = 200) {
|
|
121
|
-
this._headers = {};
|
|
122
126
|
this._body = body;
|
|
123
127
|
this._headers = headers;
|
|
124
128
|
this._statusCode = statusCode;
|
|
@@ -171,8 +175,9 @@ var ResponseEntity = class {
|
|
|
171
175
|
* ensuring type safety when constructing the response.
|
|
172
176
|
*/
|
|
173
177
|
var ResponseEntityBuilder = class {
|
|
178
|
+
_statusCode;
|
|
179
|
+
_headers = {};
|
|
174
180
|
constructor(statusCode) {
|
|
175
|
-
this._headers = {};
|
|
176
181
|
this._statusCode = statusCode;
|
|
177
182
|
}
|
|
178
183
|
/**
|
|
@@ -204,6 +209,7 @@ var ResponseEntityBuilder = class {
|
|
|
204
209
|
* @see {@link Sapling.loadResponseStatusErrorMiddleware}
|
|
205
210
|
*/
|
|
206
211
|
var ResponseStatusError = class ResponseStatusError extends Error {
|
|
212
|
+
status;
|
|
207
213
|
constructor(status, message) {
|
|
208
214
|
super(message ?? "Something went wrong.");
|
|
209
215
|
this.status = status;
|
|
@@ -215,150 +221,30 @@ var ResponseStatusError = class ResponseStatusError extends Error {
|
|
|
215
221
|
//#endregion
|
|
216
222
|
//#region src/helper/error/parse.ts
|
|
217
223
|
/**
|
|
218
|
-
* This error should be thrown when some data cannot be parsed by a given schema.
|
|
224
|
+
* This error should be thrown when some data cannot be parsed by a given Standard Schema compatible schema.
|
|
219
225
|
*/
|
|
220
226
|
var ParserError = class ParserError extends ResponseStatusError {
|
|
221
|
-
constructor(location, issues, vendor) {
|
|
222
|
-
super(400, ParserError.formatMessage(location, issues, vendor));
|
|
227
|
+
constructor(location, issues, vendor, functionName) {
|
|
228
|
+
super(400, ParserError.formatMessage(location, issues, vendor, functionName));
|
|
223
229
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
224
230
|
}
|
|
225
|
-
static formatMessage(location, issues, vendor) {
|
|
231
|
+
static formatMessage(location, issues, vendor, functionName) {
|
|
226
232
|
const formatted = issues.map((i) => {
|
|
227
233
|
const path = Array.isArray(i.path) ? i.path.map((seg) => typeof seg === "object" && seg ? String(seg.key) : String(seg)).join(".") : "";
|
|
228
234
|
return path ? `${path}: ${i.message}` : i.message;
|
|
229
235
|
}).join("; ");
|
|
230
|
-
return
|
|
231
|
-
switch (location) {
|
|
232
|
-
case "reqbody": return "request body";
|
|
233
|
-
case "reqparams": return "request params";
|
|
234
|
-
case "reqquery": return "request query";
|
|
235
|
-
}
|
|
236
|
-
})()}: ${formatted}`;
|
|
237
|
-
}
|
|
238
|
-
};
|
|
239
|
-
//#endregion
|
|
240
|
-
//#region src/helper/sapling.ts
|
|
241
|
-
const settings = {
|
|
242
|
-
serialize: JSON.stringify,
|
|
243
|
-
deserialize: JSON.parse
|
|
244
|
-
};
|
|
245
|
-
/**
|
|
246
|
-
* Collection of utility functions which are essential for Sapling to function.
|
|
247
|
-
*/
|
|
248
|
-
var Sapling = class Sapling {
|
|
249
|
-
/**
|
|
250
|
-
* If you would prefer to manually resolve your controllers instead, call resolve
|
|
251
|
-
* on the controller class.
|
|
252
|
-
*
|
|
253
|
-
* @example```ts
|
|
254
|
-
* import { Sapling } from "@tahminator/sapling";
|
|
255
|
-
* import TestController from "./path/to/test.controller";
|
|
256
|
-
*
|
|
257
|
-
* const app = express();
|
|
258
|
-
*
|
|
259
|
-
* const router = Sapling.resolve(TestController);
|
|
260
|
-
* app.use(router);
|
|
261
|
-
* ```
|
|
262
|
-
*/
|
|
263
|
-
static resolve(clazz) {
|
|
264
|
-
const router = _ControllerRegistry.get(clazz);
|
|
265
|
-
if (!router) throw new Error("Controller cannot be found");
|
|
266
|
-
return router;
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Register this function as a middleware in order to utilize Sapling's `deserialize` function.
|
|
270
|
-
*
|
|
271
|
-
* @example```ts
|
|
272
|
-
* import { Sapling } from "@tahminator/sapling";
|
|
273
|
-
* import express from "express";
|
|
274
|
-
*
|
|
275
|
-
* const app = express();
|
|
276
|
-
*
|
|
277
|
-
* app.use(Sapling.json());
|
|
278
|
-
* ```
|
|
279
|
-
*/
|
|
280
|
-
static json() {
|
|
281
|
-
return (request, _response, next) => {
|
|
282
|
-
try {
|
|
283
|
-
if (!request.body) return next();
|
|
284
|
-
if (request.headers["content-type"] !== "application/json") return next();
|
|
285
|
-
if (typeof request.body === "string") request.body = Sapling.deserialize(request.body);
|
|
286
|
-
else if (typeof request.body === "object") {
|
|
287
|
-
const raw = JSON.stringify(request.body);
|
|
288
|
-
request.body = Sapling.deserialize(raw);
|
|
289
|
-
}
|
|
290
|
-
next();
|
|
291
|
-
} catch (err) {
|
|
292
|
-
next(err);
|
|
293
|
-
}
|
|
294
|
-
};
|
|
236
|
+
return `Failed to parse ${this.getPrettyLocationString(location)} with ${vendor} on ${functionName}: ${formatted}`;
|
|
295
237
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
* const app = express();
|
|
304
|
-
*
|
|
305
|
-
* app.registerApp(app);
|
|
306
|
-
* ```
|
|
307
|
-
*/
|
|
308
|
-
static registerApp(app) {
|
|
309
|
-
app.use(e.text({ type: "application/json" }));
|
|
310
|
-
app.use(Sapling.json());
|
|
311
|
-
}
|
|
312
|
-
/**
|
|
313
|
-
* Serialize a value into a JSON string.
|
|
314
|
-
*
|
|
315
|
-
* This function is used in {@link ResponseEntity} to serialize the `body`.
|
|
316
|
-
*
|
|
317
|
-
* Use `setSerializeFn` to override underlying implementation.
|
|
318
|
-
*
|
|
319
|
-
* @defaultValue `JSON.stringify`
|
|
320
|
-
*/
|
|
321
|
-
static serialize(value) {
|
|
322
|
-
return settings.serialize(value);
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* Replace the function used for `serialize`.
|
|
326
|
-
*/
|
|
327
|
-
static setSerializeFn(fn) {
|
|
328
|
-
settings.serialize = fn;
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* De-serialize a JSON string back to a JavaScript object.
|
|
332
|
-
*
|
|
333
|
-
* This function is used to de-serialize a string into a `body`.
|
|
334
|
-
*
|
|
335
|
-
* Use `setDeserializeFn` to override underlying implementation.
|
|
336
|
-
*
|
|
337
|
-
* @defaultValue `JSON.parse`
|
|
338
|
-
*/
|
|
339
|
-
static deserialize(value) {
|
|
340
|
-
return settings.deserialize(value);
|
|
341
|
-
}
|
|
342
|
-
/**
|
|
343
|
-
* Replace the function used for `deserialize`
|
|
344
|
-
*/
|
|
345
|
-
static setDeserializeFn(fn) {
|
|
346
|
-
settings.deserialize = fn;
|
|
238
|
+
static getPrettyLocationString(location) {
|
|
239
|
+
switch (location) {
|
|
240
|
+
case "reqbody": return "request body";
|
|
241
|
+
case "reqparams": return "request params";
|
|
242
|
+
case "reqquery": return "request query";
|
|
243
|
+
case "resbody": return "response body";
|
|
244
|
+
}
|
|
347
245
|
}
|
|
348
246
|
};
|
|
349
247
|
//#endregion
|
|
350
|
-
//#region src/types.ts
|
|
351
|
-
const methodResolve = {
|
|
352
|
-
GET: "get",
|
|
353
|
-
PUT: "put",
|
|
354
|
-
POST: "post",
|
|
355
|
-
DELETE: "delete",
|
|
356
|
-
OPTIONS: "options",
|
|
357
|
-
PATCH: "patch",
|
|
358
|
-
HEAD: "head",
|
|
359
|
-
USE: "use"
|
|
360
|
-
};
|
|
361
|
-
//#endregion
|
|
362
248
|
//#region lib/weakmap.ts
|
|
363
249
|
/**
|
|
364
250
|
* WeakMap that is iterable.
|
|
@@ -479,132 +365,220 @@ function _resolve(ctor) {
|
|
|
479
365
|
return _InjectableRegistry.get(ctor);
|
|
480
366
|
}
|
|
481
367
|
//#endregion
|
|
482
|
-
//#region
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
* You can then just simply cast `request.body` for your use
|
|
489
|
-
*
|
|
490
|
-
* @example
|
|
491
|
-
* ```ts
|
|
492
|
-
* const CREATE_BOOK_REQUEST_BODY_SCHEMA = z.object({
|
|
493
|
-
* name: z.string(),
|
|
494
|
-
* description: z.string().optional(),
|
|
495
|
-
* });
|
|
496
|
-
*
|
|
497
|
-
* ⠀@Controller({ prefix: "/api/book" })
|
|
498
|
-
* class BookController {
|
|
499
|
-
* ⠀@RequestBody(CREATE_BOOK_REQUEST_BODY_SCHEMA)
|
|
500
|
-
* ⠀@POST()
|
|
501
|
-
* public createBook(request: e.Request) {
|
|
502
|
-
* const { name, description } = request.body as unknown as z.infer<
|
|
503
|
-
* typeof CREATE_BOOK_REQUEST_BODY_SCHEMA
|
|
504
|
-
* >;
|
|
505
|
-
* }
|
|
506
|
-
* }
|
|
507
|
-
* ```
|
|
508
|
-
*/
|
|
509
|
-
function RequestBody(schema) {
|
|
510
|
-
return (target, propertyKey) => {
|
|
511
|
-
const ctor = target.constructor;
|
|
512
|
-
const fnName = String(propertyKey);
|
|
513
|
-
_setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "body", schema, fnName);
|
|
514
|
-
};
|
|
515
|
-
}
|
|
516
|
-
/**
|
|
517
|
-
* Apply to a route method to have `request.param` be parsed by `schema`.
|
|
518
|
-
*
|
|
519
|
-
* This annotation will parse `request.param` & then override `request.param`.
|
|
520
|
-
* You can then just simply cast `request.param` for your use
|
|
521
|
-
*
|
|
522
|
-
* @example
|
|
523
|
-
* ```ts
|
|
524
|
-
* const GET_BOOK_REQUEST_PARAM_SCHEMA = z.object({
|
|
525
|
-
* bookId: z.string(),
|
|
526
|
-
* });
|
|
527
|
-
*
|
|
528
|
-
* ⠀@Controller({ prefix: "/api/book" })
|
|
529
|
-
* class BookController {
|
|
530
|
-
* ⠀@RequestParam(GET_BOOK_REQUEST_PARAM_SCHEMA)
|
|
531
|
-
* ⠀@GET("/:bookId")
|
|
532
|
-
* public getBook(request: e.Request) {
|
|
533
|
-
* const { bookId } = request.param as unknown as z.infer<
|
|
534
|
-
* typeof GET_BOOK_REQUEST_PARAM_SCHEMA
|
|
535
|
-
* >;
|
|
536
|
-
* }
|
|
537
|
-
* }
|
|
538
|
-
* ```
|
|
539
|
-
*/
|
|
540
|
-
function RequestParam(schema) {
|
|
541
|
-
return (target, propertyKey) => {
|
|
542
|
-
const ctor = target.constructor;
|
|
543
|
-
const fnName = String(propertyKey);
|
|
544
|
-
_setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "param", schema, fnName);
|
|
545
|
-
};
|
|
368
|
+
//#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
|
|
369
|
+
function __decorate(decorators, target, key, desc) {
|
|
370
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
371
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
372
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
373
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
546
374
|
}
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/middleware/health/registrar.ts
|
|
377
|
+
let HealthRegistrar = class HealthRegistrar {
|
|
378
|
+
_checks;
|
|
379
|
+
_sealed;
|
|
380
|
+
constructor() {
|
|
381
|
+
this._checks = [];
|
|
382
|
+
this._sealed = false;
|
|
383
|
+
}
|
|
384
|
+
add(healthCheck) {
|
|
385
|
+
this._checks.push(healthCheck);
|
|
386
|
+
}
|
|
387
|
+
seal() {
|
|
388
|
+
this._sealed = true;
|
|
389
|
+
}
|
|
390
|
+
async check() {
|
|
391
|
+
if (!this._sealed) return false;
|
|
392
|
+
return (await Promise.all(this._checks.map((c) => c()))).every((c) => c === true);
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
HealthRegistrar = __decorate([Injectable()], HealthRegistrar);
|
|
396
|
+
//#endregion
|
|
397
|
+
//#region src/helper/sapling.ts
|
|
398
|
+
const _settings = {
|
|
399
|
+
serialize: JSON.stringify,
|
|
400
|
+
deserialize: JSON.parse,
|
|
401
|
+
health: { path: "/up" },
|
|
402
|
+
doc: {
|
|
403
|
+
openApiPath: "/openapi.json",
|
|
404
|
+
swaggerPath: "/swagger.html",
|
|
405
|
+
metadata: {
|
|
406
|
+
title: "API",
|
|
407
|
+
version: "1.0.0"
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
};
|
|
547
411
|
/**
|
|
548
|
-
*
|
|
549
|
-
*
|
|
550
|
-
* This annotation will parse `request.query` & then override `request.query`.
|
|
551
|
-
* You can then just simply cast `request.query` for your use
|
|
552
|
-
*
|
|
553
|
-
* @example
|
|
554
|
-
* ```ts
|
|
555
|
-
* const LIST_BOOKS_REQUEST_QUERY_SCHEMA = z.object({
|
|
556
|
-
* sort: z.enum(["name", "createdAt"]).optional(),
|
|
557
|
-
* q: z.string().optional(),
|
|
558
|
-
* });
|
|
559
|
-
*
|
|
560
|
-
* ⠀@Controller({ prefix: "/api/book" })
|
|
561
|
-
* class BookController {
|
|
562
|
-
* ⠀@RequestQuery(LIST_BOOKS_REQUEST_QUERY_SCHEMA)
|
|
563
|
-
* ⠀@GET()
|
|
564
|
-
* public listBooks(request: e.Request) {
|
|
565
|
-
* const { sort, q } = request.query as unknown as z.infer<
|
|
566
|
-
* typeof LIST_BOOKS_REQUEST_QUERY_SCHEMA
|
|
567
|
-
* >;
|
|
568
|
-
* }
|
|
569
|
-
* }
|
|
570
|
-
* ```
|
|
412
|
+
* Collection of utility functions which are essential for Sapling to function.
|
|
571
413
|
*/
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
return created;
|
|
592
|
-
}
|
|
593
|
-
function _setOnce(def, key, schema, fnName) {
|
|
594
|
-
if (def[key]) throw new Error(`Duplicate request schema for "${String(key)}" on method "${fnName}"`);
|
|
595
|
-
def[key] = schema;
|
|
596
|
-
}
|
|
597
|
-
function _getRequestSchemas(ctor, fnName) {
|
|
598
|
-
return _requestSchemaStore.get(ctor)?.get(fnName);
|
|
599
|
-
}
|
|
600
|
-
async function _parseOrThrow(schema, input, kind) {
|
|
601
|
-
const result = await schema["~standard"].validate(input);
|
|
602
|
-
if (result.issues) {
|
|
603
|
-
console.debug(`Failed to parse a schema`);
|
|
604
|
-
throw new ParserError(kind, result.issues, schema["~standard"].vendor);
|
|
414
|
+
var Sapling = class Sapling {
|
|
415
|
+
/**
|
|
416
|
+
* If you would prefer to manually resolve your controllers instead, call resolve
|
|
417
|
+
* on the controller class.
|
|
418
|
+
*
|
|
419
|
+
* @example```ts
|
|
420
|
+
* import { Sapling } from "@tahminator/sapling";
|
|
421
|
+
* import TestController from "./path/to/test.controller";
|
|
422
|
+
*
|
|
423
|
+
* const app = express();
|
|
424
|
+
*
|
|
425
|
+
* const router = Sapling.resolve(TestController);
|
|
426
|
+
* app.use(router);
|
|
427
|
+
* ```
|
|
428
|
+
*/
|
|
429
|
+
static resolve(clazz) {
|
|
430
|
+
const router = _ControllerRegistry.get(clazz);
|
|
431
|
+
if (!router) throw new Error("Controller cannot be found");
|
|
432
|
+
return router;
|
|
605
433
|
}
|
|
606
|
-
|
|
607
|
-
|
|
434
|
+
/**
|
|
435
|
+
* Register this function as a middleware in order to utilize Sapling's `deserialize` function.
|
|
436
|
+
*
|
|
437
|
+
* @example```ts
|
|
438
|
+
* import { Sapling } from "@tahminator/sapling";
|
|
439
|
+
* import express from "express";
|
|
440
|
+
*
|
|
441
|
+
* const app = express();
|
|
442
|
+
*
|
|
443
|
+
* app.use(Sapling.json());
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
static json() {
|
|
447
|
+
return (request, _response, next) => {
|
|
448
|
+
try {
|
|
449
|
+
if (!request.body) return next();
|
|
450
|
+
if (request.headers["content-type"] !== "application/json") return next();
|
|
451
|
+
if (typeof request.body === "string") request.body = Sapling.deserialize(request.body);
|
|
452
|
+
else if (typeof request.body === "object") {
|
|
453
|
+
const raw = JSON.stringify(request.body);
|
|
454
|
+
request.body = Sapling.deserialize(raw);
|
|
455
|
+
}
|
|
456
|
+
next();
|
|
457
|
+
} catch (err) {
|
|
458
|
+
next(err);
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Register your application with all the necessary middlewares and logics for Sapling to function.
|
|
464
|
+
*
|
|
465
|
+
* @example```ts
|
|
466
|
+
* import { Sapling } from "@tahminator/sapling";
|
|
467
|
+
* import express from "express";
|
|
468
|
+
*
|
|
469
|
+
* const app = express();
|
|
470
|
+
*
|
|
471
|
+
* app.registerApp(app);
|
|
472
|
+
* ```
|
|
473
|
+
*/
|
|
474
|
+
static registerApp(app) {
|
|
475
|
+
app.use(e.text({ type: "application/json" }));
|
|
476
|
+
app.use(Sapling.json());
|
|
477
|
+
_InjectableRegistry.get(HealthRegistrar)?.seal();
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Serialize a value into a JSON string.
|
|
481
|
+
*
|
|
482
|
+
* This function is used in {@link ResponseEntity} to serialize the `body`.
|
|
483
|
+
*
|
|
484
|
+
* Use `setSerializeFn` to override underlying implementation.
|
|
485
|
+
*
|
|
486
|
+
* @defaultValue `JSON.stringify`
|
|
487
|
+
*/
|
|
488
|
+
static serialize(value) {
|
|
489
|
+
return _settings.serialize(value);
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Replace the function used for `serialize`.
|
|
493
|
+
*/
|
|
494
|
+
static setSerializeFn(fn) {
|
|
495
|
+
_settings.serialize = fn;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* De-serialize a JSON string back to a JavaScript object.
|
|
499
|
+
*
|
|
500
|
+
* This function is used to de-serialize a string into a `body`.
|
|
501
|
+
*
|
|
502
|
+
* Use `setDeserializeFn` to override underlying implementation.
|
|
503
|
+
*
|
|
504
|
+
* @defaultValue `JSON.parse`
|
|
505
|
+
*/
|
|
506
|
+
static deserialize(value) {
|
|
507
|
+
return _settings.deserialize(value);
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Replace the function used for `deserialize`
|
|
511
|
+
*/
|
|
512
|
+
static setDeserializeFn(fn) {
|
|
513
|
+
_settings.deserialize = fn;
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Modify extra settings
|
|
517
|
+
*/
|
|
518
|
+
static Extras = {
|
|
519
|
+
/**
|
|
520
|
+
* Modify default settings applied to OpenAPI & Swagger
|
|
521
|
+
*/
|
|
522
|
+
swaggerAndOpenApi: {
|
|
523
|
+
/**
|
|
524
|
+
* Set base OpenAPI metadata values.
|
|
525
|
+
*
|
|
526
|
+
* @default { title: "API", version: "1.0.0" }
|
|
527
|
+
*/
|
|
528
|
+
setMetadata(metadata) {
|
|
529
|
+
_settings.doc.metadata = metadata;
|
|
530
|
+
},
|
|
531
|
+
/**
|
|
532
|
+
* change default endpoint that will serve OpenAPI spec.
|
|
533
|
+
* Swagger will also load this endpoint on load.
|
|
534
|
+
*
|
|
535
|
+
* @default `/openapi.json`
|
|
536
|
+
*/
|
|
537
|
+
setOpenApiPath(path) {
|
|
538
|
+
_settings.doc.openApiPath = path;
|
|
539
|
+
},
|
|
540
|
+
/**
|
|
541
|
+
* change Swagger endpoint.
|
|
542
|
+
*
|
|
543
|
+
* @default `/swagger.html`
|
|
544
|
+
*/
|
|
545
|
+
setSwaggerPath(path) {
|
|
546
|
+
_settings.doc.swaggerPath = path;
|
|
547
|
+
}
|
|
548
|
+
} };
|
|
549
|
+
/**
|
|
550
|
+
* This method can be used in a `@MiddlewareClass` to register any libraries
|
|
551
|
+
* that expect you to register multiple registers at once. An example is `swagger-ui-express`
|
|
552
|
+
*
|
|
553
|
+
* @example
|
|
554
|
+
* ```ts
|
|
555
|
+
* ⠀@MiddlewareClass()
|
|
556
|
+
* class Serve {
|
|
557
|
+
* // `swagger.serve` returns multiple Express handlers for all the assets and routes
|
|
558
|
+
* // that will be served
|
|
559
|
+
* private readonly handlers: RequestHandler[] = swagger.serve;
|
|
560
|
+
*
|
|
561
|
+
* ⠀@Middleware(_settings.doc.swaggerPath)
|
|
562
|
+
* handle(request: Request, response: Response, next: NextFunction) {
|
|
563
|
+
* return Sapling.chainHandlers(this.handlers, request, response, next);
|
|
564
|
+
* }
|
|
565
|
+
* }
|
|
566
|
+
* ```
|
|
567
|
+
*/
|
|
568
|
+
static chainHandlers(handlers, request, response, next, index = 0) {
|
|
569
|
+
if (index >= handlers.length) {
|
|
570
|
+
next();
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
handlers[index]?.(request, response, (err) => {
|
|
574
|
+
if (err) {
|
|
575
|
+
next(err);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
Sapling.chainHandlers(handlers, request, response, next, index + 1);
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
};
|
|
608
582
|
//#endregion
|
|
609
583
|
//#region src/annotation/route.ts
|
|
610
584
|
const _routeStore = /* @__PURE__ */ new WeakMap();
|
|
@@ -687,6 +661,245 @@ function _getRoutes(ctor) {
|
|
|
687
661
|
return _routeStore.get(ctor) ?? [];
|
|
688
662
|
}
|
|
689
663
|
//#endregion
|
|
664
|
+
//#region src/annotation/schema.ts
|
|
665
|
+
function ControllerSchema(options) {
|
|
666
|
+
return (target) => {
|
|
667
|
+
_setControllerSchema(target, options);
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function RouteSchema(options) {
|
|
671
|
+
return (target, propertyKey) => {
|
|
672
|
+
const ctor = target.constructor;
|
|
673
|
+
_setRouteSchema(ctor, String(propertyKey), options);
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
const _routeSchemaStore = /* @__PURE__ */ new WeakMap();
|
|
677
|
+
const _controllerSchemaStore = /* @__PURE__ */ new WeakMap();
|
|
678
|
+
function getOrCreateRouteSchemaStore(store, ctor) {
|
|
679
|
+
const existing = store.get(ctor);
|
|
680
|
+
if (existing) return existing;
|
|
681
|
+
const created = /* @__PURE__ */ new Map();
|
|
682
|
+
store.set(ctor, created);
|
|
683
|
+
return created;
|
|
684
|
+
}
|
|
685
|
+
function _setRouteSchema(ctor, fnName, options) {
|
|
686
|
+
getOrCreateRouteSchemaStore(_routeSchemaStore, ctor).set(fnName, options);
|
|
687
|
+
}
|
|
688
|
+
function _setControllerSchema(ctor, options) {
|
|
689
|
+
_controllerSchemaStore.set(ctor, options);
|
|
690
|
+
}
|
|
691
|
+
function _getRouteSchema(ctor, fnName) {
|
|
692
|
+
return _routeSchemaStore.get(ctor)?.get(fnName);
|
|
693
|
+
}
|
|
694
|
+
function _getControllerSchema(ctor) {
|
|
695
|
+
return _controllerSchemaStore.get(ctor);
|
|
696
|
+
}
|
|
697
|
+
//#endregion
|
|
698
|
+
//#region src/annotation/validator.ts
|
|
699
|
+
const _validatorSchemaStore = /* @__PURE__ */ new WeakMap();
|
|
700
|
+
function ResponseBody(schema) {
|
|
701
|
+
return (target, propertyKey) => {
|
|
702
|
+
const ctor = target.constructor;
|
|
703
|
+
const fnName = String(propertyKey);
|
|
704
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "responseBody", schema, fnName);
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
function RequestBody(schema) {
|
|
708
|
+
return (target, propertyKey) => {
|
|
709
|
+
const ctor = target.constructor;
|
|
710
|
+
const fnName = String(propertyKey);
|
|
711
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestBody", schema, fnName);
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
function RequestParam(schema) {
|
|
715
|
+
return (target, propertyKey) => {
|
|
716
|
+
const ctor = target.constructor;
|
|
717
|
+
const fnName = String(propertyKey);
|
|
718
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestParam", schema, fnName);
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
function RequestQuery(schema) {
|
|
722
|
+
return (target, propertyKey) => {
|
|
723
|
+
const ctor = target.constructor;
|
|
724
|
+
const fnName = String(propertyKey);
|
|
725
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestQuery", schema, fnName);
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
function getOrCreateValidatorSchemaStore(store, ctor) {
|
|
729
|
+
const existing = store.get(ctor);
|
|
730
|
+
if (existing) return existing;
|
|
731
|
+
const created = /* @__PURE__ */ new Map();
|
|
732
|
+
store.set(ctor, created);
|
|
733
|
+
return created;
|
|
734
|
+
}
|
|
735
|
+
function _getOrCreateSchemaDefinition(ctor, fnName) {
|
|
736
|
+
const byFn = getOrCreateValidatorSchemaStore(_validatorSchemaStore, ctor);
|
|
737
|
+
const existing = byFn.get(fnName);
|
|
738
|
+
if (existing) return existing;
|
|
739
|
+
const created = {};
|
|
740
|
+
byFn.set(fnName, created);
|
|
741
|
+
return created;
|
|
742
|
+
}
|
|
743
|
+
async function _parseOrThrow(schema, input, location, fnName) {
|
|
744
|
+
const result = await schema["~standard"].validate(input);
|
|
745
|
+
if (result.issues) throw new ParserError(location, result.issues, schema["~standard"].vendor, fnName);
|
|
746
|
+
return result.value;
|
|
747
|
+
}
|
|
748
|
+
function _saveValidatorSchema(def, key, schema, fnName) {
|
|
749
|
+
if (def[key]) throw new Error(`Duplicate schema for "${String(key)}" on method "${fnName}"`);
|
|
750
|
+
def[key] = schema;
|
|
751
|
+
}
|
|
752
|
+
function _getValidatorSchema(ctor, fnName) {
|
|
753
|
+
return _validatorSchemaStore.get(ctor)?.get(fnName);
|
|
754
|
+
}
|
|
755
|
+
//#endregion
|
|
756
|
+
//#region src/helper/openapi.ts
|
|
757
|
+
var OpenAPIGenerator = class {
|
|
758
|
+
OPENAPI_VERSION = "3.0.0";
|
|
759
|
+
controllers = /* @__PURE__ */ new Set();
|
|
760
|
+
registerController(controllerClass, prefix) {
|
|
761
|
+
this.controllers.add({
|
|
762
|
+
class: controllerClass,
|
|
763
|
+
prefix
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* visible for testing
|
|
768
|
+
*/
|
|
769
|
+
_clearControllers() {
|
|
770
|
+
this.controllers.clear();
|
|
771
|
+
}
|
|
772
|
+
get metadata() {
|
|
773
|
+
return _settings.doc.metadata;
|
|
774
|
+
}
|
|
775
|
+
generateSpec() {
|
|
776
|
+
const metadata = this.metadata;
|
|
777
|
+
const paths = {};
|
|
778
|
+
const tags = [];
|
|
779
|
+
for (const { class: controllerClass, prefix } of this.controllers) {
|
|
780
|
+
const routes = _getRoutes(controllerClass);
|
|
781
|
+
const controllerSchema = _getControllerSchema(controllerClass);
|
|
782
|
+
if (controllerSchema?.title) tags.push({
|
|
783
|
+
name: controllerSchema.title,
|
|
784
|
+
description: controllerSchema.description
|
|
785
|
+
});
|
|
786
|
+
for (const route of routes) {
|
|
787
|
+
if (route.method === "USE") continue;
|
|
788
|
+
const schemas = _getValidatorSchema(controllerClass, route.fnName);
|
|
789
|
+
const routeSchema = _getRouteSchema(controllerClass, route.fnName);
|
|
790
|
+
if (route.path instanceof RegExp) throw new Error(`You have a route with a regex path of ${route.path.source}. This is not compatible with OpenAPI.`);
|
|
791
|
+
const openApiPath = (prefix + route.path).replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
792
|
+
if (!paths[openApiPath]) paths[openApiPath] = {};
|
|
793
|
+
const responses = {};
|
|
794
|
+
if (schemas?.responseBody) {
|
|
795
|
+
const responseSchema = this.toJsonSchema(schemas.responseBody, "output");
|
|
796
|
+
responses["200"] = {
|
|
797
|
+
description: responseSchema.description ?? "Successful response",
|
|
798
|
+
content: { "application/json": { schema: responseSchema } }
|
|
799
|
+
};
|
|
800
|
+
} else responses["200"] = { description: "Successful response" };
|
|
801
|
+
if (routeSchema?.responses) for (const resp of routeSchema.responses) {
|
|
802
|
+
const statusCode = String(resp.statusCode);
|
|
803
|
+
const existingResponse = responses[statusCode];
|
|
804
|
+
const existingSchema = existingResponse && "content" in existingResponse ? existingResponse.content?.["application/json"]?.schema : void 0;
|
|
805
|
+
const responseSchema = resp.schema ? this.toJsonSchema(resp.schema, "output") : statusCode === "200" ? existingSchema : void 0;
|
|
806
|
+
responses[statusCode] = {
|
|
807
|
+
...existingResponse,
|
|
808
|
+
description: resp.description ?? responseSchema?.description ?? existingResponse?.description ?? `Response ${resp.statusCode}`,
|
|
809
|
+
...responseSchema ? { content: { "application/json": { schema: responseSchema } } } : {}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
const operation = {
|
|
813
|
+
responses,
|
|
814
|
+
summary: routeSchema?.summary,
|
|
815
|
+
description: routeSchema?.description,
|
|
816
|
+
tags: controllerSchema?.title ? [controllerSchema.title] : void 0
|
|
817
|
+
};
|
|
818
|
+
const parameters = [];
|
|
819
|
+
if (schemas?.requestParam) {
|
|
820
|
+
const paramSchema = this.toJsonSchema(schemas.requestParam, "input");
|
|
821
|
+
if (paramSchema.type === "object" && paramSchema.properties) for (const [name, schema] of Object.entries(paramSchema.properties)) {
|
|
822
|
+
const parameterSchema = schema;
|
|
823
|
+
parameters.push({
|
|
824
|
+
name,
|
|
825
|
+
in: "path",
|
|
826
|
+
required: true,
|
|
827
|
+
description: parameterSchema.description,
|
|
828
|
+
schema: parameterSchema
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (schemas?.requestQuery) {
|
|
833
|
+
const querySchema = this.toJsonSchema(schemas.requestQuery, "input");
|
|
834
|
+
if (querySchema.type === "object" && querySchema.properties) for (const [name, schema] of Object.entries(querySchema.properties)) {
|
|
835
|
+
const isRequired = Array.isArray(querySchema.required) && querySchema.required.includes(name);
|
|
836
|
+
const parameterSchema = schema;
|
|
837
|
+
parameters.push({
|
|
838
|
+
name,
|
|
839
|
+
in: "query",
|
|
840
|
+
required: isRequired,
|
|
841
|
+
description: parameterSchema.description,
|
|
842
|
+
schema: parameterSchema
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
if (parameters.length > 0) operation.parameters = parameters;
|
|
847
|
+
if (schemas?.requestBody) {
|
|
848
|
+
const requestSchema = this.toJsonSchema(schemas.requestBody, "input");
|
|
849
|
+
operation.requestBody = {
|
|
850
|
+
required: true,
|
|
851
|
+
description: requestSchema.description,
|
|
852
|
+
content: { "application/json": { schema: requestSchema } }
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
const method = route.method.toLowerCase();
|
|
856
|
+
paths[openApiPath][method] = operation;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
return {
|
|
860
|
+
openapi: this.OPENAPI_VERSION,
|
|
861
|
+
info: {
|
|
862
|
+
title: metadata.title,
|
|
863
|
+
version: metadata.version,
|
|
864
|
+
description: metadata.description
|
|
865
|
+
},
|
|
866
|
+
tags: tags.length > 0 ? tags : void 0,
|
|
867
|
+
paths
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
toJsonSchema(schema, direction = "output") {
|
|
871
|
+
try {
|
|
872
|
+
const jsonSchema = schema["~standard"].jsonSchema;
|
|
873
|
+
return direction === "input" ? jsonSchema.input({ target: "openapi-3.0" }) : jsonSchema.output({ target: "openapi-3.0" });
|
|
874
|
+
} catch (e) {
|
|
875
|
+
if (e instanceof Error && e.message.includes("Transforms cannot be represented in JSON Schema")) throw new Error(`${e.message}.\nIt appears that you are using z.transform() - it is highly recommended that you use z.codec instead - https://zod.dev/codecs`, { cause: e });
|
|
876
|
+
throw e;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
const openApiGenerator = new OpenAPIGenerator();
|
|
881
|
+
function _registerController(controllerClass, prefix) {
|
|
882
|
+
openApiGenerator.registerController(controllerClass, prefix);
|
|
883
|
+
}
|
|
884
|
+
function generateOpenApiSpec() {
|
|
885
|
+
return openApiGenerator.generateSpec();
|
|
886
|
+
}
|
|
887
|
+
function _clearOpenApiRegistry() {
|
|
888
|
+
openApiGenerator._clearControllers();
|
|
889
|
+
}
|
|
890
|
+
//#endregion
|
|
891
|
+
//#region src/types.ts
|
|
892
|
+
const methodResolve = {
|
|
893
|
+
GET: "get",
|
|
894
|
+
PUT: "put",
|
|
895
|
+
POST: "post",
|
|
896
|
+
DELETE: "delete",
|
|
897
|
+
OPTIONS: "options",
|
|
898
|
+
PATCH: "patch",
|
|
899
|
+
HEAD: "head",
|
|
900
|
+
USE: "use"
|
|
901
|
+
};
|
|
902
|
+
//#endregion
|
|
690
903
|
//#region src/annotation/controller.ts
|
|
691
904
|
const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
|
|
692
905
|
/**
|
|
@@ -698,6 +911,7 @@ const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
|
|
|
698
911
|
function Controller({ prefix = "", deps = [] } = {}) {
|
|
699
912
|
return (target) => {
|
|
700
913
|
const targetClass = target;
|
|
914
|
+
_registerController(target, prefix);
|
|
701
915
|
const router = Router();
|
|
702
916
|
const routes = _getRoutes(target);
|
|
703
917
|
const usedRoutes = /* @__PURE__ */ new Set();
|
|
@@ -722,15 +936,20 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
|
|
|
722
936
|
if (method === "USE" && fn.length >= 4) {
|
|
723
937
|
const middlewareFn = async (err, request, response, next) => {
|
|
724
938
|
try {
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
939
|
+
await validate({
|
|
940
|
+
target,
|
|
941
|
+
fnName,
|
|
942
|
+
request
|
|
943
|
+
});
|
|
944
|
+
await handleResult({
|
|
945
|
+
result: fn.bind(controllerInstance)(err, request, response, next),
|
|
946
|
+
response,
|
|
947
|
+
target,
|
|
948
|
+
fnName,
|
|
949
|
+
method,
|
|
950
|
+
path: path instanceof RegExp ? path.source : fp,
|
|
951
|
+
isErrorMiddleware: true
|
|
952
|
+
});
|
|
734
953
|
} catch (e) {
|
|
735
954
|
console.error(e);
|
|
736
955
|
next(e);
|
|
@@ -740,34 +959,52 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
|
|
|
740
959
|
return;
|
|
741
960
|
}
|
|
742
961
|
router[methodName](fp, async (request, response, next) => {
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
}
|
|
756
|
-
const result = await fn.bind(controllerInstance)(request, response, next);
|
|
757
|
-
if (result instanceof ResponseEntity) {
|
|
758
|
-
response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(result.getBody()));
|
|
759
|
-
return;
|
|
760
|
-
}
|
|
761
|
-
if (result instanceof RedirectView) {
|
|
762
|
-
response.redirect(result.getUrl());
|
|
763
|
-
return;
|
|
764
|
-
}
|
|
765
|
-
if (method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${methodName.toUpperCase()} ${path instanceof RegExp ? path.source : fp}`));
|
|
962
|
+
await validate({
|
|
963
|
+
target,
|
|
964
|
+
fnName,
|
|
965
|
+
request
|
|
966
|
+
});
|
|
967
|
+
await handleResult({
|
|
968
|
+
result: await fn.bind(controllerInstance)(request, response, next),
|
|
969
|
+
response,
|
|
970
|
+
target,
|
|
971
|
+
fnName,
|
|
972
|
+
method,
|
|
973
|
+
path: path instanceof RegExp ? path.source : fp
|
|
974
|
+
});
|
|
766
975
|
});
|
|
767
976
|
}
|
|
768
977
|
_ControllerRegistry.set(targetClass, router);
|
|
769
978
|
};
|
|
770
979
|
}
|
|
980
|
+
async function handleResult({ result, target, fnName, response, method, path, isErrorMiddleware = false }) {
|
|
981
|
+
const schemas = _getValidatorSchema(target, fnName);
|
|
982
|
+
if (result instanceof ResponseEntity) {
|
|
983
|
+
const body = schemas && schemas.responseBody ? await _parseOrThrow(schemas.responseBody, result.getBody(), "resbody", fnName) : result.getBody();
|
|
984
|
+
response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(body));
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (result instanceof RedirectView) {
|
|
988
|
+
response.redirect(result.getUrl());
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (!isErrorMiddleware && method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${method} ${path}`));
|
|
992
|
+
}
|
|
993
|
+
async function validate({ target, fnName, request }) {
|
|
994
|
+
const schemas = _getValidatorSchema(target, fnName);
|
|
995
|
+
if (schemas) {
|
|
996
|
+
if (schemas.requestBody) request.body = await _parseOrThrow(schemas.requestBody, request.body, "reqbody", fnName);
|
|
997
|
+
if (schemas.requestParam) request.params = await _parseOrThrow(schemas.requestParam, request.params, "reqparams", fnName);
|
|
998
|
+
if (schemas.requestQuery) {
|
|
999
|
+
const parsedQuery = await _parseOrThrow(schemas.requestQuery, request.query, "reqquery", fnName);
|
|
1000
|
+
Object.defineProperty(request, "query", {
|
|
1001
|
+
value: parsedQuery,
|
|
1002
|
+
writable: true,
|
|
1003
|
+
configurable: true
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
771
1008
|
//#endregion
|
|
772
1009
|
//#region src/annotation/middleware.ts
|
|
773
1010
|
/**
|
|
@@ -781,15 +1018,7 @@ function MiddlewareClass(...args) {
|
|
|
781
1018
|
return Controller(...args);
|
|
782
1019
|
}
|
|
783
1020
|
//#endregion
|
|
784
|
-
//#region
|
|
785
|
-
function __decorate(decorators, target, key, desc) {
|
|
786
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
787
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
788
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
789
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
790
|
-
}
|
|
791
|
-
//#endregion
|
|
792
|
-
//#region src/middleware/default/base.ts
|
|
1021
|
+
//#region src/middleware/default/error/base.ts
|
|
793
1022
|
let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
|
|
794
1023
|
handle(err, _request, _response, _next) {
|
|
795
1024
|
console.error("[Error]", err);
|
|
@@ -799,7 +1028,20 @@ let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
|
|
|
799
1028
|
__decorate([Middleware()], DefaultBaseErrorMiddleware.prototype, "handle", null);
|
|
800
1029
|
DefaultBaseErrorMiddleware = __decorate([MiddlewareClass()], DefaultBaseErrorMiddleware);
|
|
801
1030
|
//#endregion
|
|
802
|
-
//#region src/middleware/default/
|
|
1031
|
+
//#region src/middleware/default/error/parse.ts
|
|
1032
|
+
let DefaultParserErrorMiddleware = class DefaultParserErrorMiddleware {
|
|
1033
|
+
handle(err, _request, _response, next) {
|
|
1034
|
+
if (err instanceof ParserError) {
|
|
1035
|
+
console.warn(err);
|
|
1036
|
+
return ResponseEntity.status(err.status).body({ message: err.message });
|
|
1037
|
+
}
|
|
1038
|
+
next(err);
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
__decorate([Middleware()], DefaultParserErrorMiddleware.prototype, "handle", null);
|
|
1042
|
+
DefaultParserErrorMiddleware = __decorate([MiddlewareClass()], DefaultParserErrorMiddleware);
|
|
1043
|
+
//#endregion
|
|
1044
|
+
//#region src/middleware/default/error/responsestatus.ts
|
|
803
1045
|
let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddleware {
|
|
804
1046
|
handle(err, _request, _response, next) {
|
|
805
1047
|
if (err instanceof ResponseStatusError) return ResponseEntity.status(err.status).body({ message: err.message });
|
|
@@ -809,4 +1051,99 @@ let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddl
|
|
|
809
1051
|
__decorate([Middleware()], DefaultResponseStatusErrorMiddleware.prototype, "handle", null);
|
|
810
1052
|
DefaultResponseStatusErrorMiddleware = __decorate([MiddlewareClass()], DefaultResponseStatusErrorMiddleware);
|
|
811
1053
|
//#endregion
|
|
812
|
-
|
|
1054
|
+
//#region src/middleware/default/openapi/index.ts
|
|
1055
|
+
let DefaultOpenApiMiddleware = class DefaultOpenApiMiddleware {
|
|
1056
|
+
handle(_request, _response, _next) {
|
|
1057
|
+
return ResponseEntity.ok().body(generateOpenApiSpec());
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
__decorate([GET(_settings.doc.openApiPath)], DefaultOpenApiMiddleware.prototype, "handle", null);
|
|
1061
|
+
DefaultOpenApiMiddleware = __decorate([MiddlewareClass()], DefaultOpenApiMiddleware);
|
|
1062
|
+
//#endregion
|
|
1063
|
+
//#region src/middleware/default/swagger/index.ts
|
|
1064
|
+
/**
|
|
1065
|
+
* Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
|
|
1066
|
+
*
|
|
1067
|
+
* Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
|
|
1068
|
+
*
|
|
1069
|
+
* You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
|
|
1070
|
+
*
|
|
1071
|
+
* ```ts
|
|
1072
|
+
* const middlewares = [
|
|
1073
|
+
* DefaultOpenApiMiddleware,
|
|
1074
|
+
* DefaultSwaggerMiddleware.Serve,
|
|
1075
|
+
* DefaultSwaggerMiddleware.Setup,
|
|
1076
|
+
* ];
|
|
1077
|
+
* middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
|
|
1078
|
+
* ```
|
|
1079
|
+
*/
|
|
1080
|
+
let Serve = class Serve {
|
|
1081
|
+
handlers = swagger.serve;
|
|
1082
|
+
handle(request, response, next) {
|
|
1083
|
+
return Sapling.chainHandlers(this.handlers, request, response, next);
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
__decorate([Middleware(_settings.doc.swaggerPath)], Serve.prototype, "handle", null);
|
|
1087
|
+
Serve = __decorate([MiddlewareClass()], Serve);
|
|
1088
|
+
/**
|
|
1089
|
+
* Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
|
|
1090
|
+
*
|
|
1091
|
+
* Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
|
|
1092
|
+
*
|
|
1093
|
+
* You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
|
|
1094
|
+
*
|
|
1095
|
+
* ```ts
|
|
1096
|
+
* const middlewares = [
|
|
1097
|
+
* DefaultOpenApiMiddleware,
|
|
1098
|
+
* DefaultSwaggerMiddleware.Serve,
|
|
1099
|
+
* DefaultSwaggerMiddleware.Setup,
|
|
1100
|
+
* ];
|
|
1101
|
+
* middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
|
|
1102
|
+
* ```
|
|
1103
|
+
*/
|
|
1104
|
+
let Setup = class Setup {
|
|
1105
|
+
handler;
|
|
1106
|
+
constructor() {
|
|
1107
|
+
this.handler = swagger.setup(null, { swaggerOptions: { url: _settings.doc.openApiPath } });
|
|
1108
|
+
}
|
|
1109
|
+
handle(request, response, next) {
|
|
1110
|
+
return this.handler(request, response, next);
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
__decorate([Middleware(_settings.doc.swaggerPath)], Setup.prototype, "handle", null);
|
|
1114
|
+
Setup = __decorate([MiddlewareClass()], Setup);
|
|
1115
|
+
/**
|
|
1116
|
+
* Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
|
|
1117
|
+
*
|
|
1118
|
+
* Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
|
|
1119
|
+
*
|
|
1120
|
+
* You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
|
|
1121
|
+
*
|
|
1122
|
+
* ```ts
|
|
1123
|
+
* const middlewares = [
|
|
1124
|
+
* DefaultOpenApiMiddleware,
|
|
1125
|
+
* DefaultSwaggerMiddleware.Serve,
|
|
1126
|
+
* DefaultSwaggerMiddleware.Setup,
|
|
1127
|
+
* ];
|
|
1128
|
+
* middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
|
|
1129
|
+
* ```
|
|
1130
|
+
*/
|
|
1131
|
+
const DefaultSwaggerMiddleware = {
|
|
1132
|
+
Serve,
|
|
1133
|
+
Setup
|
|
1134
|
+
};
|
|
1135
|
+
//#endregion
|
|
1136
|
+
//#region src/middleware/default/health/index.ts
|
|
1137
|
+
let DefaultHealthMiddleware = class DefaultHealthMiddleware {
|
|
1138
|
+
constructor(healthRegistrar) {
|
|
1139
|
+
this.healthRegistrar = healthRegistrar;
|
|
1140
|
+
}
|
|
1141
|
+
async serve(_request, _response, _next) {
|
|
1142
|
+
const up = await this.healthRegistrar.check();
|
|
1143
|
+
return ResponseEntity.ok().body({ up });
|
|
1144
|
+
}
|
|
1145
|
+
};
|
|
1146
|
+
__decorate([GET(_settings.health.path)], DefaultHealthMiddleware.prototype, "serve", null);
|
|
1147
|
+
DefaultHealthMiddleware = __decorate([MiddlewareClass({ deps: [HealthRegistrar] })], DefaultHealthMiddleware);
|
|
1148
|
+
//#endregion
|
|
1149
|
+
export { Controller, ControllerSchema, DELETE, DefaultBaseErrorMiddleware, DefaultHealthMiddleware, DefaultOpenApiMiddleware, DefaultParserErrorMiddleware, DefaultResponseStatusErrorMiddleware, DefaultSwaggerMiddleware, GET, HEAD, HealthRegistrar, Html404ErrorPage, HttpStatus, Injectable, Middleware, MiddlewareClass, OPTIONS, PATCH, POST, PUT, ParserError, RedirectView, RequestBody, RequestParam, RequestQuery, ResponseBody, ResponseEntity, ResponseEntityBuilder, ResponseStatusError, RouteSchema, Sapling, _ControllerRegistry, _InjectableDeps, _InjectableRegistry, _Route, _clearOpenApiRegistry, _getControllerSchema, _getOrCreateSchemaDefinition, _getRouteSchema, _getRoutes, _getValidatorSchema, _parseOrThrow, _registerController, _resolve, _saveValidatorSchema, _setControllerSchema, _setRouteSchema, _settings, generateOpenApiSpec, methodResolve, openApiGenerator };
|