@sepo27/servicio 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +71 -10
  3. package/dist/src/@spec/index.d.ts +1 -1
  4. package/dist/src/@spec/index.js +1 -1
  5. package/dist/src/@spec/tbench/TBench.d.ts +6 -0
  6. package/dist/src/@spec/tbench/TBench.js +7 -0
  7. package/dist/src/@spec/tbench/TMock.d.ts +10 -0
  8. package/dist/src/@spec/tbench/TMock.js +53 -0
  9. package/dist/src/@spec/tbench/index.d.ts +2 -0
  10. package/dist/src/@spec/tbench/index.js +2 -0
  11. package/dist/src/@spec/tbench/types.d.ts +15 -0
  12. package/dist/src/@spec/tbench/types.js +1 -0
  13. package/dist/src/index.d.ts +12 -2
  14. package/dist/src/index.js +12 -2
  15. package/dist/src/lib/express/types.d.ts +2 -1
  16. package/dist/src/lib/express/types.js +29 -28
  17. package/dist/src/main/app/App.d.ts +3 -0
  18. package/dist/src/main/app/App.js +1 -0
  19. package/dist/src/main/app/AppX.d.ts +9 -0
  20. package/dist/src/main/app/AppX.js +14 -0
  21. package/dist/src/main/app/AppX.spec.d.ts +1 -0
  22. package/dist/src/main/app/AppX.spec.js +17 -0
  23. package/dist/src/main/app/errorHandler.d.ts +10 -0
  24. package/dist/src/main/app/errorHandler.js +21 -0
  25. package/dist/src/main/app/errorHandler.spec.d.ts +1 -0
  26. package/dist/src/main/app/errorHandler.spec.js +56 -0
  27. package/dist/src/main/app/servicio.spec.d.ts +1 -0
  28. package/dist/src/main/app/servicio.spec.js +119 -0
  29. package/dist/src/main/factories/makeApp.d.ts +2 -0
  30. package/dist/src/main/factories/makeApp.js +7 -0
  31. package/dist/src/main/factories/makeApp.spec.d.ts +1 -0
  32. package/dist/src/main/factories/makeApp.spec.js +19 -0
  33. package/dist/src/main/factories/makeRoute.d.ts +3 -0
  34. package/dist/src/main/factories/makeRoute.js +2 -0
  35. package/dist/src/main/factories/makeRoute.spec.d.ts +1 -0
  36. package/dist/src/main/factories/makeRoute.spec.js +21 -0
  37. package/dist/src/main/factories/makeRouter.d.ts +2 -0
  38. package/dist/src/main/factories/makeRouter.js +7 -0
  39. package/dist/src/main/factories/makeRouter.spec.d.ts +1 -0
  40. package/dist/src/main/factories/makeRouter.spec.js +24 -0
  41. package/dist/src/main/factories/mixinProxy.d.ts +3 -0
  42. package/dist/src/main/factories/mixinProxy.js +41 -0
  43. package/dist/src/main/factories/mixinProxy.spec.d.ts +1 -0
  44. package/dist/src/main/factories/mixinProxy.spec.js +43 -0
  45. package/dist/src/main/routing/Routable.d.ts +12 -0
  46. package/dist/src/main/routing/Routable.js +16 -0
  47. package/dist/src/main/routing/Routable.spec.d.ts +1 -0
  48. package/dist/src/main/routing/Routable.spec.js +39 -0
  49. package/dist/src/main/routing/Route.d.ts +13 -0
  50. package/dist/src/main/routing/Route.js +51 -0
  51. package/dist/src/main/routing/Route.spec.d.ts +1 -0
  52. package/dist/src/main/routing/Route.spec.js +86 -0
  53. package/dist/src/main/routing/Router.d.ts +3 -0
  54. package/dist/src/main/routing/Router.js +1 -0
  55. package/dist/src/main/routing/RouterX.d.ts +6 -0
  56. package/dist/src/main/routing/RouterX.js +7 -0
  57. package/dist/src/main/routing/RouterX.spec.d.ts +1 -0
  58. package/dist/src/main/routing/RouterX.spec.js +15 -0
  59. package/dist/src/main/types.d.ts +5 -10
  60. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## 0.5.0 (2026-12-05)
2
+
3
+ * refaactor: Refactor complete approach to use namespace solution ([4006cd3](https://github.com/sepo27/servicio/commit/4006cd3))
4
+ * feat: Setup Router logic ([1e90ae4](https://github.com/sepo27/servicio/commit/1e90ae4))
5
+ * feat: Add Router support ([7d15d8b](https://github.com/sepo27/servicio/commit/7d15d8b))
6
+ * chore(agents): Add TBench agent skills ([5fc23b4](https://github.com/sepo27/servicio/commit/5fc23b4))
7
+ * chore: Setup basic agent skills ([23f50bb](https://github.com/sepo27/servicio/commit/23f50bb))
8
+ * chore: Add eslint rule to omit interface delimiters ([1d3b2f9](https://github.com/sepo27/servicio/commit/1d3b2f9))
9
+ * test: Reorg spec tbench ([fc0b007](https://github.com/sepo27/servicio/commit/fc0b007))
10
+
1
11
  ## 0.4.0 (2026-11-26)
2
12
 
3
13
  * feat: Refactor addRoute() to useRoute() ([3258451](https://github.com/sepo27/servicio/commit/3258451))
package/README.md CHANGED
@@ -2,15 +2,15 @@
2
2
 
3
3
  **! ACTIVE DEVELOPMENT !**
4
4
 
5
- # Purpose
5
+ # What
6
6
 
7
7
  Backend Service Frame.
8
- *(Based on express JS)*
8
+ *(Extension of express JS)*
9
9
 
10
10
  **Features:**
11
11
  - lightweight *(as express JS itself)*
12
12
  - reusable routes abstraction
13
- - returnable http response (from route handler)
13
+ - simplified router actions (with returning responses)
14
14
 
15
15
  # Quick Start
16
16
 
@@ -23,11 +23,11 @@ pnpm install @sepo27/servicio
23
23
 
24
24
  Use
25
25
  ```typescript
26
- import { Route, servicio, HttpStatus, SuccessResponse } from '@sepo27/servicio';
26
+ import { svc, HttpStatus, SuccessResponse } from '@sepo27/servicio';
27
27
 
28
- const app = servicio();
28
+ const app: svc.App = svc.app();
29
29
 
30
- const fooRoute = new Route('GET /foo', () => {
30
+ app.useRoute('GET /foo', () => {
31
31
  return new SuccessResponse({
32
32
  status: HttpStatus.OK,
33
33
  body: {
@@ -36,8 +36,6 @@ const fooRoute = new Route('GET /foo', () => {
36
36
  });
37
37
  });
38
38
 
39
- app.useRoute(fooRoute);
40
-
41
39
  app.listen(3000, () => {
42
40
  console.log('=== Servicio listening on port 3000');
43
41
  });
@@ -45,9 +43,72 @@ app.listen(3000, () => {
45
43
 
46
44
  # Usage
47
45
 
46
+ ## Common cases
47
+
48
+ Reusable routes
49
+
50
+ ```typescript
51
+ import { svc, SuccessResponse } from '@sepo27/servicio';
52
+
53
+ const app: svc.App = svc.app()
54
+
55
+ const fooRoute: svc.Route = svc.route('GET /foo', () => new SuccessResponse())
56
+
57
+ app.useRoute(fooRoute)
58
+ ```
59
+
60
+ Router
61
+
62
+ ```typescript
63
+ import { svc, SuccessResponse, HttpStatus } from '@sepo27/servicio';
64
+
65
+ const app: svc.App = svc.app()
66
+
67
+ const router: svc.Router = svc.router('/foo')
68
+ router.useRoute('GET /', () => new SuccessResponse({
69
+ status: HttpStatus.OK,
70
+ body: {
71
+ items: ['foo'],
72
+ },
73
+ }))
74
+
75
+ app.useRouter(router)
76
+ ```
77
+
78
+ Nested Router
79
+
80
+ ```typescript
81
+ import { svc, SuccessResponse, HttpStatus } from '@sepo27/servicio';
82
+
83
+ const app: svc.App = svc.app()
84
+
85
+ const router: svc.Router = svc.router('/foo')
86
+ router.useRoute('GET /', () => new SuccessResponse({
87
+ status: HttpStatus.OK,
88
+ body: {
89
+ items: ['foo'],
90
+ },
91
+ }))
92
+
93
+ const fooItemsRouter: svc.Router = svc.router('/:id/items')
94
+ fooItemsRouter.useRoute('GET /', () => new SuccessResponse({
95
+ status: HttpStatus.OK,
96
+ body: {
97
+ items: ['bar']
98
+ },
99
+ }))
100
+
101
+ router.useRouter(fooItemsRouter)
102
+
103
+ app.useRouter(router)
104
+ ```
105
+
106
+ **:warning: A bug is present where path params are missing in nested routers' actions / handlers**
107
+ **:warning: Presently "mixin" objects' methods (`App` / `Router`) do not support chaining**
108
+
48
109
  ## Express JS wrapper
49
110
 
50
- `servicio()` factory returns an object which is a combined instance of `Express` and `ServicioApp` classes.
111
+ `svc.app()` factory returns an object instance "mixin" of `AppX` and `Express` classes.
51
112
  So all express functionality is preserved as is.
52
113
 
53
114
  ## Http Meta
@@ -63,7 +124,7 @@ If instance of `HttpError` is thrown with optional `headers` it will be caught &
63
124
  However, body isn't handled by default.
64
125
  Use servicio default error handler instead to fully support `HttpError`s:
65
126
  ```typescript
66
- const app = servicio();
127
+ const app = svc.app();
67
128
 
68
129
  // Add routes here ...
69
130
 
@@ -1 +1 @@
1
- export { TMock } from './mock/TMock.js';
1
+ export * from './tbench/index.js';
@@ -1 +1 @@
1
- export { TMock } from './mock/TMock.js';
1
+ export * from './tbench/index.js';
@@ -0,0 +1,6 @@
1
+ import { TMock } from './TMock.js';
2
+ export declare class TBench {
3
+ constructor();
4
+ readonly mock: TMock;
5
+ reset(): void;
6
+ }
@@ -0,0 +1,7 @@
1
+ import { TMock } from './TMock.js';
2
+ export class TBench {
3
+ constructor() {
4
+ this.mock = new TMock();
5
+ }
6
+ reset() { this.mock.reset(); }
7
+ }
@@ -0,0 +1,10 @@
1
+ import { ExpressMock } from './types.js';
2
+ export declare class TMock {
3
+ /*** Public ***/
4
+ get express(): ExpressMock;
5
+ reset(): void;
6
+ /*** Private ***/
7
+ private mockCache;
8
+ private makeStructMock;
9
+ private getMock;
10
+ }
@@ -0,0 +1,53 @@
1
+ import { ExpressMethod } from '../../lib/express/types.js';
2
+ export class TMock {
3
+ constructor() {
4
+ /*** Public ***/
5
+ /*** Private ***/
6
+ this.mockCache = {};
7
+ }
8
+ get express() {
9
+ const tmock = this;
10
+ return {
11
+ get req() {
12
+ return {};
13
+ },
14
+ get res() {
15
+ return {
16
+ status: jest.fn().mockReturnThis(),
17
+ set: jest.fn().mockReturnThis(),
18
+ send: jest.fn().mockReturnThis(),
19
+ };
20
+ },
21
+ get next() {
22
+ return tmock.getMock('express.next', () => jest.fn());
23
+ },
24
+ getRoutable(key = 'express.routable') {
25
+ const mock = Object.values(ExpressMethod).reduce((acc, method) => Object.assign(acc, {
26
+ [method]: jest.fn(),
27
+ }), {});
28
+ return tmock.makeStructMock(key, mock);
29
+ },
30
+ };
31
+ }
32
+ reset() {
33
+ this.mockCache = {};
34
+ jest.resetAllMocks();
35
+ }
36
+ makeStructMock(key, struct) {
37
+ const self = this;
38
+ return Object.keys(struct).reduce((acc, prop) => Object.defineProperty(acc, prop, {
39
+ get() {
40
+ const propKey = [key, prop].join('.');
41
+ return self.getMock(propKey, () => struct[prop]);
42
+ },
43
+ }), {});
44
+ }
45
+ getMock(key, factory) {
46
+ if (key in this.mockCache) {
47
+ return this.mockCache[key];
48
+ }
49
+ const mock = factory();
50
+ this.mockCache[key] = mock;
51
+ return mock;
52
+ }
53
+ }
@@ -0,0 +1,2 @@
1
+ export { TMock } from './TMock.js';
2
+ export { TBench } from './TBench.js';
@@ -0,0 +1,2 @@
1
+ export { TMock } from './TMock.js';
2
+ export { TBench } from './TBench.js';
@@ -0,0 +1,15 @@
1
+ import express from 'express';
2
+ import { ExpressMethod } from '../../lib/express/types.js';
3
+ export type ExpressRequestMock = express.Request & {};
4
+ export type ExpressResponseMock = express.Response & {
5
+ status: jest.Mock;
6
+ set: jest.Mock;
7
+ send: jest.Mock;
8
+ };
9
+ export type ExpressRoutableMock = express.IRouter & Record<ExpressMethod, jest.Mock>;
10
+ export interface ExpressMock {
11
+ get req(): ExpressRequestMock;
12
+ get res(): ExpressResponseMock;
13
+ get next(): express.NextFunction;
14
+ getRoutable(key?: string): ExpressRoutableMock;
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,13 @@
1
- export { servicio } from './main/servicio.js';
2
- export { Route } from './main/Route.js';
1
+ import type { App as AppType } from './main/app/App.js';
2
+ import { Route as RouteClass } from './main/routing/Route.js';
3
+ import type { Router as RouterType } from './main/routing/Router.js';
4
+ export declare namespace svc {
5
+ const app: () => AppType;
6
+ const route: (endpoint: import("./main/types.js").RouteEndpointParam, action: import("./main/types.js").RouteAction) => RouteClass;
7
+ const Route: typeof RouteClass;
8
+ const router: (path: string) => RouterType;
9
+ type App = AppType;
10
+ type Route = RouteClass;
11
+ type Router = RouterType;
12
+ }
3
13
  export * from './lib/http-meta/index.js';
package/dist/src/index.js CHANGED
@@ -1,3 +1,13 @@
1
- export { servicio } from './main/servicio.js';
2
- export { Route } from './main/Route.js';
1
+ import { makeApp } from './main/factories/makeApp.js';
2
+ import { makeRoute } from './main/factories/makeRoute.js';
3
+ import { makeRouter } from './main/factories/makeRouter.js';
4
+ import { Route as RouteClass } from './main/routing/Route.js';
5
+ export var svc;
6
+ (function (svc) {
7
+ // Logic
8
+ svc.app = makeApp;
9
+ svc.route = makeRoute;
10
+ svc.Route = RouteClass;
11
+ svc.router = makeRouter;
12
+ })(svc || (svc = {}));
3
13
  export * from './lib/http-meta/index.js';
@@ -1,5 +1,6 @@
1
1
  export type ExpressPathParams = string | RegExp | Array<string | RegExp>;
2
- export declare enum ExpressHttpMethod {
2
+ export declare enum ExpressMethod {
3
+ USE = "use",
3
4
  CONNECT = "connect",
4
5
  COPY = "copy",
5
6
  DELETE = "delete",
@@ -1,38 +1,39 @@
1
- export var ExpressHttpMethod;
2
- (function (ExpressHttpMethod) {
1
+ export var ExpressMethod;
2
+ (function (ExpressMethod) {
3
3
  // ACL = 'acl',
4
4
  // BIND = 'bind',
5
5
  // CHECKOUT = 'checkout',
6
- ExpressHttpMethod["CONNECT"] = "connect";
7
- ExpressHttpMethod["COPY"] = "copy";
8
- ExpressHttpMethod["DELETE"] = "delete";
9
- ExpressHttpMethod["GET"] = "get";
10
- ExpressHttpMethod["HEAD"] = "head";
11
- ExpressHttpMethod["LINK"] = "link";
12
- ExpressHttpMethod["LOCK"] = "lock";
6
+ ExpressMethod["USE"] = "use";
7
+ ExpressMethod["CONNECT"] = "connect";
8
+ ExpressMethod["COPY"] = "copy";
9
+ ExpressMethod["DELETE"] = "delete";
10
+ ExpressMethod["GET"] = "get";
11
+ ExpressMethod["HEAD"] = "head";
12
+ ExpressMethod["LINK"] = "link";
13
+ ExpressMethod["LOCK"] = "lock";
13
14
  // M_SEARCH = 'm-search',
14
15
  // MERGE = 'merge',
15
16
  // MKACTIVITY = 'mkactivity',
16
17
  // MKCALENDAR = 'mkcalendar',
17
- ExpressHttpMethod["MKCOL"] = "mkcol";
18
- ExpressHttpMethod["MOVE"] = "move";
19
- ExpressHttpMethod["NOTIFY"] = "notify";
20
- ExpressHttpMethod["OPTIONS"] = "options";
21
- ExpressHttpMethod["PATCH"] = "patch";
22
- ExpressHttpMethod["POST"] = "post";
23
- ExpressHttpMethod["PROPFIND"] = "propfind";
24
- ExpressHttpMethod["PROPPATCH"] = "proppatch";
25
- ExpressHttpMethod["PURGE"] = "purge";
26
- ExpressHttpMethod["PUT"] = "put";
27
- ExpressHttpMethod["QUERY"] = "query";
18
+ ExpressMethod["MKCOL"] = "mkcol";
19
+ ExpressMethod["MOVE"] = "move";
20
+ ExpressMethod["NOTIFY"] = "notify";
21
+ ExpressMethod["OPTIONS"] = "options";
22
+ ExpressMethod["PATCH"] = "patch";
23
+ ExpressMethod["POST"] = "post";
24
+ ExpressMethod["PROPFIND"] = "propfind";
25
+ ExpressMethod["PROPPATCH"] = "proppatch";
26
+ ExpressMethod["PURGE"] = "purge";
27
+ ExpressMethod["PUT"] = "put";
28
+ ExpressMethod["QUERY"] = "query";
28
29
  // REBIND = 'rebind',
29
- ExpressHttpMethod["REPORT"] = "report";
30
- ExpressHttpMethod["SEARCH"] = "search";
30
+ ExpressMethod["REPORT"] = "report";
31
+ ExpressMethod["SEARCH"] = "search";
31
32
  // SOURCE = 'source',
32
- ExpressHttpMethod["SUBSCRIBE"] = "subscribe";
33
- ExpressHttpMethod["TRACE"] = "trace";
33
+ ExpressMethod["SUBSCRIBE"] = "subscribe";
34
+ ExpressMethod["TRACE"] = "trace";
34
35
  // UNBIND = 'unbind',
35
- ExpressHttpMethod["UNLINK"] = "unlink";
36
- ExpressHttpMethod["UNLOCK"] = "unlock";
37
- ExpressHttpMethod["UNSUBSCRIBE"] = "unsubscribe";
38
- })(ExpressHttpMethod || (ExpressHttpMethod = {}));
36
+ ExpressMethod["UNLINK"] = "unlink";
37
+ ExpressMethod["UNLOCK"] = "unlock";
38
+ ExpressMethod["UNSUBSCRIBE"] = "unsubscribe";
39
+ })(ExpressMethod || (ExpressMethod = {}));
@@ -0,0 +1,3 @@
1
+ import type express from 'express';
2
+ import type { AppX } from './AppX.js';
3
+ export type App = AppX & express.Express;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import express from 'express';
2
+ import { Routable } from '../routing/Routable.js';
3
+ export declare class AppX extends Routable<express.Express> {
4
+ constructor(expressApp: express.Express);
5
+ /**
6
+ * Use default Servicio error handler.
7
+ */
8
+ useErrorHandler(): this;
9
+ }
@@ -0,0 +1,14 @@
1
+ import { Routable } from '../routing/Routable.js';
2
+ import { errorHandler } from './errorHandler.js';
3
+ export class AppX extends Routable {
4
+ constructor(expressApp) {
5
+ super(expressApp);
6
+ }
7
+ /**
8
+ * Use default Servicio error handler.
9
+ */
10
+ useErrorHandler() {
11
+ this.irouter.use(errorHandler);
12
+ return this;
13
+ }
14
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import { TBench } from '../../@spec/index.js';
2
+ import { errorHandler } from './errorHandler.js';
3
+ import { AppX } from './AppX.js';
4
+ describe('AppX', () => {
5
+ let bench;
6
+ beforeEach(() => {
7
+ bench = new TBench();
8
+ });
9
+ afterEach(() => {
10
+ bench.reset();
11
+ });
12
+ it('useErrorHandler() registers the default error handler', () => {
13
+ const expressApp = bench.mock.express.getRoutable('app'), app = new AppX(expressApp);
14
+ expect(app.useErrorHandler()).toBe(app);
15
+ expect(expressApp.use).toHaveBeenCalledWith(errorHandler);
16
+ });
17
+ });
@@ -0,0 +1,10 @@
1
+ import express from 'express';
2
+ /**
3
+ * Default error handler to send errors from HttpError instances.
4
+ *
5
+ * @param err
6
+ * @param req
7
+ * @param res
8
+ * @param next
9
+ */
10
+ export declare const errorHandler: (err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => void;
@@ -0,0 +1,21 @@
1
+ import { HttpError } from '../../lib/http-meta/index.js';
2
+ /**
3
+ * Default error handler to send errors from HttpError instances.
4
+ *
5
+ * @param err
6
+ * @param req
7
+ * @param res
8
+ * @param next
9
+ */
10
+ export const errorHandler = (err, req, res, next) => {
11
+ if (err instanceof HttpError) {
12
+ if (err.headers) {
13
+ res.set(err.headers);
14
+ }
15
+ const sendArgs = err.body ? [err.body] : [];
16
+ res.status(err.status).send(...sendArgs);
17
+ }
18
+ else {
19
+ next(err);
20
+ }
21
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,56 @@
1
+ import { BadRequestError } from '../../lib/http-meta/index.js';
2
+ import { TBench } from '../../@spec/index.js';
3
+ import { errorHandler } from './errorHandler.js';
4
+ describe('errorHandler()', () => {
5
+ let bench;
6
+ beforeEach(() => {
7
+ bench = new TBench();
8
+ });
9
+ afterEach(() => {
10
+ bench.reset();
11
+ });
12
+ it('sends status of http error', () => {
13
+ const err = new BadRequestError(), resMock = bench.mock.express.res;
14
+ errorHandler(err, bench.mock.express.req, resMock, bench.mock.express.next);
15
+ expect(resMock.status).toHaveBeenCalledWith(err.status);
16
+ expect(resMock.send).toHaveBeenCalledWith();
17
+ expect(resMock.send).toHaveBeenCalledAfter(resMock.status);
18
+ expect(bench.mock.express.next).not.toHaveBeenCalled();
19
+ });
20
+ it('sends status and headers of http error', () => {
21
+ const errHeaders = { 'x-app': 'test' }, err = new BadRequestError({ headers: errHeaders }), resMock = bench.mock.express.res;
22
+ errorHandler(err, bench.mock.express.req, resMock, bench.mock.express.next);
23
+ expect(resMock.set).toHaveBeenCalledWith(err.headers);
24
+ expect(resMock.set).toHaveBeenCalledBefore(resMock.status);
25
+ expect(resMock.status).toHaveBeenCalledWith(err.status);
26
+ expect(resMock.send).toHaveBeenCalledWith();
27
+ expect(resMock.send).toHaveBeenCalledAfter(resMock.status);
28
+ expect(bench.mock.express.next).not.toHaveBeenCalled();
29
+ });
30
+ it('sends status and body of http error', () => {
31
+ const errBody = { error: 'Test error' }, err = new BadRequestError({ body: errBody }), resMock = bench.mock.express.res;
32
+ errorHandler(err, bench.mock.express.req, resMock, bench.mock.express.next);
33
+ expect(resMock.status).toHaveBeenCalledWith(err.status);
34
+ expect(resMock.send).toHaveBeenCalledWith(errBody);
35
+ expect(resMock.send).toHaveBeenCalledAfter(resMock.status);
36
+ expect(bench.mock.express.next).not.toHaveBeenCalled();
37
+ });
38
+ it('sends status, headers and body of http error', () => {
39
+ const errHeaders = { 'x-app': 'test' }, errBody = { error: 'Test error' }, err = new BadRequestError({ headers: errHeaders, body: errBody }), resMock = bench.mock.express.res;
40
+ errorHandler(err, bench.mock.express.req, resMock, bench.mock.express.next);
41
+ expect(resMock.set).toHaveBeenCalledWith(err.headers);
42
+ expect(resMock.set).toHaveBeenCalledBefore(resMock.status);
43
+ expect(resMock.status).toHaveBeenCalledWith(err.status);
44
+ expect(resMock.send).toHaveBeenCalledWith(errBody);
45
+ expect(resMock.send).toHaveBeenCalledAfter(resMock.status);
46
+ expect(bench.mock.express.next).not.toHaveBeenCalled();
47
+ });
48
+ it('passes through non-http error', () => {
49
+ const err = new Error('Unknown test error'), resMock = bench.mock.express.res;
50
+ errorHandler(err, bench.mock.express.req, resMock, bench.mock.express.next);
51
+ expect(resMock.set).not.toHaveBeenCalled();
52
+ expect(resMock.status).not.toHaveBeenCalled();
53
+ expect(resMock.send).not.toHaveBeenCalled();
54
+ expect(bench.mock.express.next).toHaveBeenCalledWith(err);
55
+ });
56
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,119 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { TBench } from '../../@spec/tbench/TBench.js';
11
+ import supertest from 'supertest';
12
+ import { svc } from '../../index.js';
13
+ import { BadRequestError, HttpStatus, InternalServerError, SuccessResponse } from '../../lib/http-meta/index.js';
14
+ /**
15
+ * Integration tests for Servicio app.
16
+ */
17
+ describe('servicio', () => {
18
+ let bench, agent, app;
19
+ beforeEach(() => {
20
+ bench = new TBench();
21
+ app = svc.app();
22
+ agent = supertest.agent(app);
23
+ });
24
+ afterEach(() => {
25
+ bench.reset();
26
+ });
27
+ it('handles simple express like native route', () => __awaiter(void 0, void 0, void 0, function* () {
28
+ app.get('/foo', (req, res) => {
29
+ res.status(200).send();
30
+ });
31
+ yield agent.get('/foo').expect(200);
32
+ }));
33
+ it('handles simple inline route', () => __awaiter(void 0, void 0, void 0, function* () {
34
+ const response = new SuccessResponse({
35
+ status: HttpStatus.OK,
36
+ body: {
37
+ mary: 'Had a little lamb',
38
+ },
39
+ });
40
+ app.useRoute('GET /abc', () => response);
41
+ yield agent
42
+ .get('/abc')
43
+ .expect(HttpStatus.OK)
44
+ .expect(res => {
45
+ expect(res.body).toEqual(response.body);
46
+ });
47
+ }));
48
+ it('handles simple route with Route class', () => __awaiter(void 0, void 0, void 0, function* () {
49
+ const response = new SuccessResponse({
50
+ status: HttpStatus.OK,
51
+ body: {
52
+ mary: 'Had a little lamb',
53
+ },
54
+ });
55
+ const route = svc.route('GET /xyz', () => response);
56
+ app.useRoute(route);
57
+ yield agent
58
+ .get('/xyz')
59
+ .expect(HttpStatus.OK)
60
+ .expect(res => {
61
+ expect(res.body).toEqual(response.body);
62
+ });
63
+ }));
64
+ it('handles router', () => __awaiter(void 0, void 0, void 0, function* () {
65
+ const router = svc.router('/foo');
66
+ router.useRoute('GET /:id', () => new SuccessResponse());
67
+ app.useRouter(router);
68
+ yield agent
69
+ .get('/foo/123')
70
+ .expect(HttpStatus.OK);
71
+ }));
72
+ it('handles nested router', () => __awaiter(void 0, void 0, void 0, function* () {
73
+ const router = svc.router('/bar');
74
+ router.useRoute('GET /:id', () => new SuccessResponse());
75
+ const itemsResponse = new SuccessResponse({
76
+ status: HttpStatus.OK,
77
+ body: { items: ['1', '2', '3'] },
78
+ }), nestedRouter = svc.router('/:id/items');
79
+ nestedRouter.useRoute('GET /', () => itemsResponse);
80
+ router.useRouter(nestedRouter);
81
+ app.useRouter(router);
82
+ yield agent
83
+ .get('/bar/123/items')
84
+ .expect(itemsResponse.status)
85
+ .expect(res => {
86
+ expect(res.body).toEqual(itemsResponse.body);
87
+ });
88
+ }));
89
+ it('handles http error with status by default (w/ express default handler)', () => __awaiter(void 0, void 0, void 0, function* () {
90
+ const error = new BadRequestError();
91
+ app.useRoute('GET /xyz', () => {
92
+ throw error;
93
+ });
94
+ yield agent.get('/xyz').expect(error.status);
95
+ }));
96
+ it('handles http error with status by error handler', () => __awaiter(void 0, void 0, void 0, function* () {
97
+ const error = new InternalServerError();
98
+ app.useRoute('GET /xyz', () => {
99
+ throw error;
100
+ });
101
+ app.useErrorHandler();
102
+ yield agent.get('/xyz').expect(error.status);
103
+ }));
104
+ it('handles http error with status and body by error handler', () => __awaiter(void 0, void 0, void 0, function* () {
105
+ const error = new BadRequestError({
106
+ body: { message: 'Test error occurred' },
107
+ }), route = svc.route('GET /baz', () => {
108
+ throw error;
109
+ });
110
+ app.useRoute(route);
111
+ app.useErrorHandler();
112
+ yield agent
113
+ .get('/baz')
114
+ .expect(error.status)
115
+ .expect(res => {
116
+ expect(res.body).toEqual(error.body);
117
+ });
118
+ }));
119
+ });
@@ -0,0 +1,2 @@
1
+ import type { App } from '../app/App.js';
2
+ export declare const makeApp: () => App;
@@ -0,0 +1,7 @@
1
+ import express from 'express';
2
+ import { AppX } from '../app/AppX.js';
3
+ import { mixinProxy } from './mixinProxy.js';
4
+ export const makeApp = () => {
5
+ const expressApp = express();
6
+ return mixinProxy(new AppX(expressApp), expressApp);
7
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import express from 'express';
2
+ import { AppX } from '../app/AppX.js';
3
+ import { makeApp } from './makeApp.js';
4
+ import { mixinProxy } from './mixinProxy.js';
5
+ jest.mock('express', () => jest.fn());
6
+ jest.mock('./mixinProxy.js', () => ({ mixinProxy: jest.fn() }));
7
+ describe('makeApp()', () => {
8
+ beforeEach(() => {
9
+ jest.clearAllMocks();
10
+ });
11
+ it('creates an app by combining AppX with Express and returns the proxy', () => {
12
+ const expressApp = {}, app = {};
13
+ jest.mocked(express).mockReturnValue(expressApp);
14
+ jest.mocked(mixinProxy).mockReturnValue(app);
15
+ expect(makeApp()).toBe(app);
16
+ expect(mixinProxy).toHaveBeenCalledTimes(1);
17
+ expect(mixinProxy).toHaveBeenCalledWith(expect.any(AppX), expressApp);
18
+ });
19
+ });
@@ -0,0 +1,3 @@
1
+ import { Route } from '../routing/Route.js';
2
+ import type { RouteAction, RouteEndpointParam } from '../types.js';
3
+ export declare const makeRoute: (endpoint: RouteEndpointParam, action: RouteAction) => Route;
@@ -0,0 +1,2 @@
1
+ import { Route } from '../routing/Route.js';
2
+ export const makeRoute = (endpoint, action) => new Route(endpoint, action);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import { HttpMethod, SuccessResponse } from '../../lib/http-meta/index.js';
2
+ import { Route } from '../routing/Route.js';
3
+ import { makeRoute } from './makeRoute.js';
4
+ jest.mock('../routing/Route.js', () => ({ Route: jest.fn() }));
5
+ describe('makeRoute()', () => {
6
+ beforeEach(() => {
7
+ jest.clearAllMocks();
8
+ });
9
+ it('calls the Route constructor with an endpoint object and action', () => {
10
+ const endpoint = { method: HttpMethod.GET, path: '/foo' }, action = () => new SuccessResponse();
11
+ makeRoute(endpoint, action);
12
+ expect(Route).toHaveBeenCalledTimes(1);
13
+ expect(Route).toHaveBeenCalledWith(endpoint, action);
14
+ });
15
+ it('calls the Route constructor with a string endpoint and action', () => {
16
+ const action = () => new SuccessResponse(), endpoint = 'POST /foo';
17
+ makeRoute(endpoint, action);
18
+ expect(Route).toHaveBeenCalledTimes(1);
19
+ expect(Route).toHaveBeenCalledWith(endpoint, action);
20
+ });
21
+ });
@@ -0,0 +1,2 @@
1
+ import type { Router } from '../routing/Router.js';
2
+ export declare const makeRouter: (path: string) => Router;
@@ -0,0 +1,7 @@
1
+ import express from 'express';
2
+ import { RouterX } from '../routing/RouterX.js';
3
+ import { mixinProxy } from './mixinProxy.js';
4
+ export const makeRouter = (path) => {
5
+ const irouter = express.Router();
6
+ return mixinProxy(new RouterX(path, irouter), irouter);
7
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ import express from 'express';
2
+ import { TBench } from '../../@spec/index.js';
3
+ import * as mixinProxyModule from './mixinProxy.js';
4
+ import { RouterX } from '../routing/RouterX.js';
5
+ import { makeRouter } from './makeRouter.js';
6
+ describe('makeRouter()', () => {
7
+ let bench;
8
+ beforeEach(() => {
9
+ bench = new TBench();
10
+ });
11
+ afterEach(() => {
12
+ jest.restoreAllMocks();
13
+ bench.reset();
14
+ });
15
+ it('creates a router by combining RouterX with Express and returns the proxy', () => {
16
+ const path = '/foo', irouter = bench.mock.express.getRoutable(), router = {};
17
+ const expressRouterMock = jest.spyOn(express, 'Router').mockReturnValue(irouter), mixinProxyMock = jest.spyOn(mixinProxyModule, 'mixinProxy').mockReturnValue(router);
18
+ expect(makeRouter(path)).toBe(router);
19
+ expect(expressRouterMock).toHaveBeenCalledTimes(1);
20
+ expect(mixinProxyMock).toHaveBeenCalledTimes(1);
21
+ expect(mixinProxyMock).toHaveBeenCalledWith(expect.any(RouterX), irouter);
22
+ expect(mixinProxyMock).toHaveBeenCalledWith(expect.objectContaining({ path }), irouter);
23
+ });
24
+ });
@@ -0,0 +1,3 @@
1
+ import { Routable } from '../routing/Routable.js';
2
+ import express from 'express';
3
+ export declare const mixinProxy: <R extends Routable<any>, I extends express.IRouter>(routable: R, irouter: I) => R & I;
@@ -0,0 +1,41 @@
1
+ export const mixinProxy = (routable, irouter) => {
2
+ const routableRecord = routable, irouterRecord = irouter;
3
+ return new Proxy(irouterRecord, {
4
+ get(_, prop) {
5
+ if (prop in routableRecord) {
6
+ const value = routableRecord[prop];
7
+ const routableDescriptor = getPropertyDescriptor(routableRecord, prop);
8
+ // Bind only Routable methods to Routable
9
+ return typeof value === 'function' && routableDescriptor && 'value' in routableDescriptor
10
+ ? value.bind(routableRecord)
11
+ : value;
12
+ }
13
+ const value = irouterRecord[prop];
14
+ return typeof value === 'function' ? value.bind(irouterRecord) : value;
15
+ },
16
+ set(_, prop, value) {
17
+ if (prop in routableRecord) {
18
+ routableRecord[prop] = value;
19
+ }
20
+ else {
21
+ irouterRecord[prop] = value;
22
+ }
23
+ return true;
24
+ },
25
+ has(_, prop) {
26
+ return prop in routableRecord || prop in irouterRecord;
27
+ },
28
+ });
29
+ };
30
+ /*** Private ***/
31
+ function getPropertyDescriptor(target, prop) {
32
+ let current = target;
33
+ while (current) {
34
+ const descriptor = Object.getOwnPropertyDescriptor(current, prop);
35
+ if (descriptor) {
36
+ return descriptor;
37
+ }
38
+ current = Object.getPrototypeOf(current);
39
+ }
40
+ return undefined;
41
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,43 @@
1
+ import express from 'express';
2
+ import { TBench } from '../../@spec/index.js';
3
+ import { mixinProxy } from './mixinProxy.js';
4
+ import { RouterX } from '../routing/RouterX.js';
5
+ describe('mixinProxy()', () => {
6
+ let bench;
7
+ beforeEach(() => {
8
+ bench = new TBench();
9
+ });
10
+ afterEach(() => {
11
+ bench.reset();
12
+ });
13
+ it('prioritizes routable properties and binds methods to their owning objects', () => {
14
+ const irouterMock = bench.mock.express.getRoutable(), routable = new RouterX('/foo', irouterMock);
15
+ irouterMock.use.mockReturnValue('bar');
16
+ const mixin = mixinProxy(routable, irouterMock);
17
+ expect(mixin.path).toBe(routable.path);
18
+ expect(mixin.use()).toBe('bar');
19
+ });
20
+ it('does not bind callable values returned by Routable getters', () => {
21
+ const irouter = express.Router(), routable = new RouterX('/foo', irouter), mixin = mixinProxy(routable, irouter);
22
+ expect(mixin.irouter).toBe(irouter);
23
+ });
24
+ // TODO
25
+ // it('routes property assignments to the object that owns the property', () => {
26
+ // const
27
+ // target = { targetOnly: 'target' },
28
+ // mixin = { mixinOnly: 'mixin' },
29
+ // proxy = mixinProxy(target, mixin);
30
+ //
31
+ // proxy.targetOnly = 'updated target';
32
+ // proxy.mixinOnly = 'updated mixin';
33
+ //
34
+ // expect(target.targetOnly).toBe('updated target');
35
+ // expect(mixin.mixinOnly).toBe('updated mixin');
36
+ // });
37
+ it('checks properties on both objects', () => {
38
+ const irouterMock = bench.mock.express.getRoutable(), routable = new RouterX('/foo', irouterMock);
39
+ const mixin = mixinProxy(routable, irouterMock);
40
+ expect('path' in mixin).toBeTruthy();
41
+ expect('use' in mixin).toBeTruthy();
42
+ });
43
+ });
@@ -0,0 +1,12 @@
1
+ import type express from 'express';
2
+ import type { Route } from './Route.js';
3
+ import type { RouteAction, RouteEndpointParam } from '../types.js';
4
+ import type { Router } from './Router.js';
5
+ export type UseRouteParams = [Route] | [RouteEndpointParam, RouteAction];
6
+ export declare abstract class Routable<R extends express.IRouter> {
7
+ private readonly irouterInstance;
8
+ useRoute(...args: UseRouteParams): void;
9
+ useRouter(router: Router): void;
10
+ get irouter(): R;
11
+ protected constructor(irouterInstance: R);
12
+ }
@@ -0,0 +1,16 @@
1
+ import { makeRoute } from '../factories/makeRoute.js';
2
+ export class Routable {
3
+ useRoute(...args) {
4
+ const route = args.length === 1 ? args[0] : makeRoute(args[0], args[1]);
5
+ this.irouter[route.method](route.path, route.handler);
6
+ }
7
+ useRouter(router) {
8
+ this.irouter.use(router.path, router.irouter);
9
+ }
10
+ get irouter() {
11
+ return this.irouterInstance;
12
+ }
13
+ constructor(irouterInstance) {
14
+ this.irouterInstance = irouterInstance;
15
+ }
16
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,39 @@
1
+ import { TBench } from '../../@spec/index.js';
2
+ import { HttpMethod, SuccessResponse } from '../../lib/http-meta/index.js';
3
+ import * as makeRouteModule from '../factories/makeRoute.js';
4
+ import { Route } from './Route.js';
5
+ import { Routable } from './Routable.js';
6
+ import { RouterX } from './RouterX.js';
7
+ describe('Routable', () => {
8
+ let bench;
9
+ beforeEach(() => {
10
+ bench = new TBench();
11
+ });
12
+ afterEach(() => {
13
+ jest.restoreAllMocks();
14
+ bench.reset();
15
+ });
16
+ it.each(Object.values(HttpMethod))('useRoute() registers a %s route with its Express method', method => {
17
+ const register = jest.fn(), router = { [method.toLowerCase()]: register }, route = new Route({ method, path: '/foo' }, () => new SuccessResponse()), routable = new TestRoutable(router);
18
+ routable.useRoute(route);
19
+ expect(register).toHaveBeenCalledTimes(1);
20
+ expect(register).toHaveBeenCalledWith(route.path, route.handler);
21
+ });
22
+ it('creates and registers a route from inline parameters', () => {
23
+ const register = jest.fn(), router = { get: register }, endpoint = { method: HttpMethod.GET, path: '/foo' }, action = () => new SuccessResponse(), route = new Route(endpoint, action), routable = new TestRoutable(router), makeRouteMock = jest.spyOn(makeRouteModule, 'makeRoute').mockReturnValue(route);
24
+ routable.useRoute(endpoint, action);
25
+ expect(makeRouteMock).toHaveBeenCalledTimes(1);
26
+ expect(makeRouteMock).toHaveBeenCalledWith(endpoint, action);
27
+ expect(register).toHaveBeenCalledWith(route.path, route.handler);
28
+ });
29
+ it('useRouter() mounts a nested router at its path', () => {
30
+ const irouterMockParent = bench.mock.express.getRoutable('parent'), irouterMockChild = bench.mock.express.getRoutable('child'), routable = new TestRoutable(irouterMockParent), router = new RouterX('/foo', irouterMockChild);
31
+ routable.useRouter(router);
32
+ expect(irouterMockParent.use).toHaveBeenCalledWith(router.path, irouterMockChild);
33
+ });
34
+ });
35
+ class TestRoutable extends Routable {
36
+ constructor(router) {
37
+ super(router);
38
+ }
39
+ }
@@ -0,0 +1,13 @@
1
+ import express from 'express';
2
+ import { ExpressMethod } from '../../lib/express/types.js';
3
+ import { RouteAction, RouteEndpoint, RouteEndpointParam } from '../types.js';
4
+ export declare class Route {
5
+ constructor(endpoint: RouteEndpointParam, action: RouteAction);
6
+ readonly endpoint: RouteEndpoint;
7
+ readonly action: RouteAction;
8
+ get path(): string;
9
+ get method(): ExpressMethod;
10
+ get handler(): express.RequestHandler;
11
+ private requestHandler;
12
+ private parseEndpoint;
13
+ }
@@ -0,0 +1,51 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { HttpMethod } from '../../lib/http-meta/index.js';
11
+ const httpMethodsList = Object.values(HttpMethod).join('|'), stringEndpointPattern = new RegExp(`^(${httpMethodsList})\\s(/.*)$`);
12
+ export class Route {
13
+ constructor(endpoint, action) {
14
+ this.requestHandler = null;
15
+ this.endpoint = typeof endpoint === 'string' ? this.parseEndpoint(endpoint) : endpoint;
16
+ this.action = action;
17
+ }
18
+ get path() {
19
+ return this.endpoint.path;
20
+ }
21
+ get method() {
22
+ return this.endpoint.method.toLowerCase();
23
+ }
24
+ get handler() {
25
+ if (this.requestHandler) {
26
+ return this.requestHandler;
27
+ }
28
+ this.requestHandler = (req, res) => __awaiter(this, void 0, void 0, function* () {
29
+ const response = yield this.action(req);
30
+ if (response.headers) {
31
+ res.set(response.headers);
32
+ }
33
+ res.status(response.status);
34
+ if (response.body === undefined) {
35
+ res.send();
36
+ }
37
+ else {
38
+ res.send(response.body);
39
+ }
40
+ });
41
+ return this.requestHandler;
42
+ }
43
+ parseEndpoint(endpoint) {
44
+ const match = endpoint.match(stringEndpointPattern);
45
+ if (!match) {
46
+ throw new Error(`Invalid route endpoint: ${endpoint}`);
47
+ }
48
+ const [, method, path] = match;
49
+ return { method: method, path };
50
+ }
51
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,86 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { ExpressMethod } from '../../lib/express/types.js';
11
+ import { HttpMethod, HttpStatus, SuccessResponse } from '../../lib/http-meta/index.js';
12
+ import { TBench } from '../../@spec/index.js';
13
+ import { Route } from './Route.js';
14
+ describe('Route', () => {
15
+ let bench;
16
+ beforeEach(() => {
17
+ bench = new TBench();
18
+ });
19
+ afterEach(() => {
20
+ bench.reset();
21
+ });
22
+ it('constructs from an endpoint object and exposes endpoint properties', () => {
23
+ const endpoint = { method: HttpMethod.POST, path: '/foo' }, action = () => new SuccessResponse(), route = new Route(endpoint, action);
24
+ expect(route.endpoint).toBe(endpoint);
25
+ expect(route.action).toBe(action);
26
+ expect(route.path).toBe(endpoint.path);
27
+ expect(route.method).toEqual('post');
28
+ });
29
+ it('parses a string endpoint into method and path', () => {
30
+ const route = new Route('PUT /bar/:id', () => new SuccessResponse());
31
+ expect(route.endpoint).toEqual({ method: HttpMethod.PUT, path: '/bar/:id' });
32
+ expect(route.path).toBe('/bar/:id');
33
+ expect(route.method).toBe(ExpressMethod.PUT);
34
+ });
35
+ it('throws for invalid endpoint strings', () => {
36
+ ['get /foo', 'POST bar', 'baz', ''].forEach(endpoint => {
37
+ expect(() => new Route(endpoint, () => new SuccessResponse()))
38
+ .toThrow(new Error(`Invalid route endpoint: ${endpoint}`));
39
+ });
40
+ });
41
+ it('invokes the action with the request', () => __awaiter(void 0, void 0, void 0, function* () {
42
+ const action = jest.fn(() => Promise.resolve(new SuccessResponse())), route = new Route('GET /foo', action), { req } = bench.mock.express;
43
+ yield runHandler(route);
44
+ expect(action).toHaveBeenCalledWith(req);
45
+ }));
46
+ it('handler() wraps to send the response status', () => __awaiter(void 0, void 0, void 0, function* () {
47
+ const response = new SuccessResponse({ status: HttpStatus.ACCEPTED }), route = new Route('GET /foo', () => response), res = yield runHandler(route);
48
+ expect(res.status).toHaveBeenCalledWith(response.status);
49
+ expect(res.send).toHaveBeenCalled();
50
+ expect(res.send).toHaveBeenCalledAfter(res.status);
51
+ }));
52
+ it('handler() wraps to send the response body', () => __awaiter(void 0, void 0, void 0, function* () {
53
+ const body = { foo: 'bar' }, response = new SuccessResponse({ status: HttpStatus.OK, body }), route = new Route('GET /foo', () => Promise.resolve(response)), res = yield runHandler(route);
54
+ expect(res.status).toHaveBeenCalledWith(response.status);
55
+ expect(res.status).toHaveBeenCalledBefore(res.send);
56
+ expect(res.send).toHaveBeenCalledWith(body);
57
+ }));
58
+ it('handler() wraps to send the response headers', () => __awaiter(void 0, void 0, void 0, function* () {
59
+ const headers = { 'x-header': 'abc' }, response = new SuccessResponse({ status: HttpStatus.OK, headers }), route = new Route('GET /foo', () => Promise.resolve(response)), res = yield runHandler(route);
60
+ expect(res.status).toHaveBeenCalledWith(response.status);
61
+ expect(res.set).toHaveBeenCalledWith(headers);
62
+ expect(res.set).toHaveBeenCalledBefore(res.send);
63
+ expect(res.send).toHaveBeenCalled();
64
+ }));
65
+ it('handler() wraps to send response status, body, and headers together', () => __awaiter(void 0, void 0, void 0, function* () {
66
+ const headers = { 'x-header': 'abc' }, body = { ok: true }, response = new SuccessResponse({ status: HttpStatus.OK, headers, body }), route = new Route('GET /foo', () => Promise.resolve(response)), res = yield runHandler(route);
67
+ expect(res.status).toHaveBeenCalledWith(response.status);
68
+ expect(res.set).toHaveBeenCalledWith(headers);
69
+ expect(res.send).toHaveBeenCalledWith(body);
70
+ }));
71
+ it('handler() wraps to send without a body when the response has none', () => __awaiter(void 0, void 0, void 0, function* () {
72
+ const response = new SuccessResponse(), route = new Route('GET /foo', () => response), res = yield runHandler(route);
73
+ expect(res.send).toHaveBeenCalledWith();
74
+ }));
75
+ it('caches and reuses the Express request handler', () => {
76
+ const route = new Route('GET /foo', () => new SuccessResponse());
77
+ expect(route.handler).toBe(route.handler);
78
+ });
79
+ function runHandler(route) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ const { req, res, next } = bench.mock.express;
82
+ yield route.handler(req, res, next);
83
+ return res;
84
+ });
85
+ }
86
+ });
@@ -0,0 +1,3 @@
1
+ import type express from 'express';
2
+ import type { RouterX } from './RouterX.js';
3
+ export type Router = RouterX & express.Router;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import express from 'express';
2
+ import { Routable } from './Routable.js';
3
+ export declare class RouterX extends Routable<express.Router> {
4
+ readonly path: string;
5
+ constructor(path: string, irouter: express.Router);
6
+ }
@@ -0,0 +1,7 @@
1
+ import { Routable } from './Routable.js';
2
+ export class RouterX extends Routable {
3
+ constructor(path, irouter) {
4
+ super(irouter);
5
+ this.path = path;
6
+ }
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ import { RouterX } from './RouterX.js';
2
+ import { TBench } from '../../@spec/index.js';
3
+ describe('RouterX', () => {
4
+ let bench;
5
+ beforeEach(() => {
6
+ bench = new TBench();
7
+ });
8
+ afterEach(() => {
9
+ bench.reset();
10
+ });
11
+ it('exposes its path', () => {
12
+ const router = new RouterX('/foo', bench.mock.express.getRoutable());
13
+ expect(router.path).toBe('/foo');
14
+ });
15
+ });
@@ -1,13 +1,8 @@
1
1
  import express from 'express';
2
2
  import { HttpMethod, HttpResponse } from '../lib/http-meta/index.js';
3
- import { ExpressPathParams } from '../lib/express/types.js';
4
- import { ServicioApp } from './ServicioApp.js';
5
- export type Servicio = ServicioApp & express.Express;
6
- export interface Request extends express.Request {
7
- }
8
- export type RouteEndpointStruct = {
3
+ export interface RouteEndpoint {
4
+ path: string;
9
5
  method: HttpMethod;
10
- path: ExpressPathParams;
11
- };
12
- export type RouteEndpoint = string | RouteEndpointStruct;
13
- export type RouteHandler = (req: Request) => HttpResponse | Promise<HttpResponse>;
6
+ }
7
+ export type RouteEndpointParam = RouteEndpoint | string;
8
+ export type RouteAction = (req: express.Request) => HttpResponse | Promise<HttpResponse>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sepo27/servicio",
3
3
  "description": "Backend Service Frame",
4
- "version": "0.4.0",
4
+ "version": "0.5.0",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",
7
7
  "types": "./dist/src/index.d.ts",
@@ -21,6 +21,7 @@
21
21
  "@commitlint/cli": "^21.2.4",
22
22
  "@commitlint/config-conventional": "^21.2.4",
23
23
  "@eslint/js": "^10.0.1",
24
+ "@stylistic/eslint-plugin": "^6.0.1",
24
25
  "@types/express": "^5.0.6",
25
26
  "@types/jest": "^30.0.0",
26
27
  "@types/node": "^26.6.6",