@feathersjs/express 5.0.0-pre.2 → 5.0.0-pre.22

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/lib/rest.d.ts CHANGED
@@ -1,21 +1,9 @@
1
- import { HookContext } from '@feathersjs/hooks';
2
- import { NullableId, Params } from '@feathersjs/feathers';
3
- import { Request, Response, NextFunction, RequestHandler } from 'express';
4
- export declare const METHOD_HEADER = "x-service-method";
5
- export interface ServiceParams {
6
- id: NullableId;
7
- data: any;
8
- params: Params;
9
- }
10
- export declare type ServiceCallback = (req: Request, res: Response, options: ServiceParams) => Promise<HookContext | any>;
11
- export declare const statusCodes: {
12
- created: number;
13
- noContent: number;
14
- methodNotAllowed: number;
15
- success: number;
1
+ import { RequestHandler } from 'express';
2
+ import { AuthenticationSettings } from './authentication';
3
+ import { Application } from './declarations';
4
+ export declare const formatter: RequestHandler;
5
+ export declare type RestOptions = {
6
+ formatter?: RequestHandler;
7
+ authentication?: AuthenticationSettings;
16
8
  };
17
- export declare const feathersParams: (req: Request, _res: Response, next: NextFunction) => void;
18
- export declare const formatter: (_req: Request, res: Response, next: NextFunction) => void;
19
- export declare const serviceMiddleware: (callback: ServiceCallback) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
20
- export declare const serviceMethodHandler: (service: any, methodName: string, getArgs: (opts: ServiceParams) => any[], headerOverride?: string) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
21
- export declare function rest(handler?: RequestHandler): (this: any, app: any) => void;
9
+ export declare const rest: (options?: RestOptions | RequestHandler) => (app: Application) => void;
package/lib/rest.js CHANGED
@@ -1,48 +1,56 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.rest = exports.serviceMethodHandler = exports.serviceMiddleware = exports.formatter = exports.feathersParams = exports.statusCodes = exports.METHOD_HEADER = void 0;
27
- const debug_1 = __importDefault(require("debug"));
3
+ exports.rest = exports.formatter = void 0;
4
+ const express_1 = require("express");
28
5
  const errors_1 = require("@feathersjs/errors");
29
- const hooks_1 = require("@feathersjs/hooks");
6
+ const commons_1 = require("@feathersjs/commons");
7
+ const transport_commons_1 = require("@feathersjs/transport-commons");
30
8
  const feathers_1 = require("@feathersjs/feathers");
31
- const express_1 = require("express");
32
9
  const authentication_1 = require("./authentication");
33
- const debug = debug_1.default('@feathersjs/express/rest');
34
- exports.METHOD_HEADER = 'x-service-method';
35
- exports.statusCodes = {
36
- created: 201,
37
- noContent: 204,
38
- methodNotAllowed: 405,
39
- success: 200
10
+ const debug = (0, commons_1.createDebug)('@feathersjs/express/rest');
11
+ const toHandler = (func) => {
12
+ return (req, res, next) => func(req, res, next).catch(error => next(error));
13
+ };
14
+ const serviceMiddleware = () => {
15
+ return toHandler(async (req, res, next) => {
16
+ const { query, headers, path, body: data, method: httpMethod } = req;
17
+ const methodOverride = req.headers[transport_commons_1.http.METHOD_HEADER];
18
+ const { service, params: { __id: id = null, ...route } = {} } = req.lookup;
19
+ const method = transport_commons_1.http.getServiceMethod(httpMethod, id, methodOverride);
20
+ const { methods } = (0, feathers_1.getServiceOptions)(service);
21
+ debug(`Found service for path ${path}, attempting to run '${method}' service method`);
22
+ if (!methods.includes(method) || feathers_1.defaultServiceMethods.includes(methodOverride)) {
23
+ const error = new errors_1.MethodNotAllowed(`Method \`${method}\` is not supported by this endpoint.`);
24
+ res.statusCode = error.code;
25
+ throw error;
26
+ }
27
+ const createArguments = transport_commons_1.http.argumentsFor[method] || transport_commons_1.http.argumentsFor.default;
28
+ const params = { query, headers, route, ...req.feathers };
29
+ const args = createArguments({ id, data, params });
30
+ const contextBase = (0, feathers_1.createContext)(service, method, { http: {} });
31
+ res.hook = contextBase;
32
+ const context = await service[method](...args, contextBase);
33
+ res.hook = context;
34
+ const response = transport_commons_1.http.getResponse(context);
35
+ res.statusCode = response.status;
36
+ res.set(response.headers);
37
+ res.data = response.body;
38
+ return next();
39
+ });
40
40
  };
41
- const feathersParams = (req, _res, next) => {
42
- req.feathers = Object.assign(Object.assign({}, req.feathers), { provider: 'rest', headers: req.headers });
43
- next();
41
+ const servicesMiddleware = () => {
42
+ return toHandler(async (req, res, next) => {
43
+ const app = req.app;
44
+ const lookup = app.lookup(req.path);
45
+ if (!lookup) {
46
+ return next();
47
+ }
48
+ req.lookup = lookup;
49
+ const options = (0, feathers_1.getServiceOptions)(lookup.service);
50
+ const middleware = options.express.composed;
51
+ return middleware(req, res, next);
52
+ });
44
53
  };
45
- exports.feathersParams = feathersParams;
46
54
  const formatter = (_req, res, next) => {
47
55
  if (res.data === undefined) {
48
56
  return next();
@@ -54,94 +62,24 @@ const formatter = (_req, res, next) => {
54
62
  });
55
63
  };
56
64
  exports.formatter = formatter;
57
- const getData = (context) => {
58
- if (!(context instanceof hooks_1.HookContext)) {
59
- return context;
60
- }
61
- return context.dispatch !== undefined
62
- ? context.dispatch
63
- : context.result;
64
- };
65
- const getStatusCode = (context, res) => {
66
- if (context instanceof hooks_1.HookContext) {
67
- if (context.statusCode) {
68
- return context.statusCode;
69
- }
70
- if (context.method === 'create') {
71
- return exports.statusCodes.created;
72
- }
73
- }
74
- if (!res.data) {
75
- return exports.statusCodes.noContent;
76
- }
77
- return exports.statusCodes.success;
78
- };
79
- const serviceMiddleware = (callback) => (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
80
- debug(`Running service middleware for '${req.url}'`);
81
- try {
82
- const { query, body: data } = req;
83
- const _a = req.params, { __feathersId: id = null } = _a, route = __rest(_a, ["__feathersId"]);
84
- const params = Object.assign({ query, route }, req.feathers);
85
- const context = yield callback(req, res, { id, data, params });
86
- res.data = getData(context);
87
- res.status(getStatusCode(context, res));
88
- next();
89
- }
90
- catch (error) {
91
- next(error);
92
- }
93
- });
94
- exports.serviceMiddleware = serviceMiddleware;
95
- const serviceMethodHandler = (service, methodName, getArgs, headerOverride) => exports.serviceMiddleware((req, res, options) => __awaiter(void 0, void 0, void 0, function* () {
96
- const methodOverride = typeof headerOverride === 'string' && req.headers[headerOverride];
97
- const method = methodOverride ? methodOverride : methodName;
98
- const { methods } = feathers_1.getServiceOptions(service);
99
- if (!methods.includes(method) || feathers_1.defaultServiceMethods.includes(methodOverride)) {
100
- res.status(exports.statusCodes.methodNotAllowed);
101
- throw new errors_1.MethodNotAllowed(`Method \`${method}\` is not supported by this endpoint.`);
102
- }
103
- const args = getArgs(options);
104
- const context = feathers_1.createContext(service, method);
105
- res.hook = context;
106
- return service[method](...args, context);
107
- }));
108
- exports.serviceMethodHandler = serviceMethodHandler;
109
- function rest(handler = exports.formatter) {
110
- return function (app) {
65
+ const rest = (options) => {
66
+ options = typeof options === 'function' ? { formatter: options } : options || {};
67
+ const formatterMiddleware = options.formatter || exports.formatter;
68
+ const authenticationOptions = options.authentication;
69
+ return (app) => {
111
70
  if (typeof app.route !== 'function') {
112
71
  throw new Error('@feathersjs/express/rest needs an Express compatible app.');
113
72
  }
114
- app.use(exports.feathersParams);
115
- app.use(authentication_1.parseAuthentication());
116
- // Register the REST provider
117
- app.mixins.push(function (service, path, options) {
118
- const { middleware: { before = [] } } = options;
119
- let { middleware: { after = [] } } = options;
120
- if (typeof handler === 'function') {
121
- after = after.concat(handler);
122
- }
123
- const baseUri = `/${path}`;
124
- const find = exports.serviceMethodHandler(service, 'find', ({ params }) => [params]);
125
- const get = exports.serviceMethodHandler(service, 'get', ({ id, params }) => [id, params]);
126
- const create = exports.serviceMethodHandler(service, 'create', ({ data, params }) => [data, params], exports.METHOD_HEADER);
127
- const update = exports.serviceMethodHandler(service, 'update', ({ id, data, params }) => [id, data, params]);
128
- const patch = exports.serviceMethodHandler(service, 'patch', ({ id, data, params }) => [id, data, params]);
129
- const remove = exports.serviceMethodHandler(service, 'remove', ({ id, params }) => [id, params]);
130
- debug(`Adding REST provider for service \`${path}\` at base route \`${baseUri}\``);
131
- const idRoute = '/:__feathersId';
132
- const serviceRouter = express_1.Router({ mergeParams: true })
133
- .get('/', find)
134
- .post('/', create)
135
- .get(idRoute, get)
136
- .put('/', update)
137
- .put(idRoute, update)
138
- .patch('/', patch)
139
- .patch(idRoute, patch)
140
- .delete('/', remove)
141
- .delete(idRoute, remove);
142
- app.use(baseUri, ...before, serviceRouter, ...after);
73
+ app.use((0, authentication_1.parseAuthentication)(authenticationOptions));
74
+ app.use(servicesMiddleware());
75
+ app.mixins.push((_service, _path, options) => {
76
+ const { express: { before = [], after = [] } = {} } = options;
77
+ const middlewares = [].concat(before, serviceMiddleware(), after, formatterMiddleware);
78
+ const middleware = (0, express_1.Router)().use(middlewares);
79
+ options.express || (options.express = {});
80
+ options.express.composed = middleware;
143
81
  });
144
82
  };
145
- }
83
+ };
146
84
  exports.rest = rest;
147
85
  //# sourceMappingURL=rest.js.map
package/lib/rest.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"rest.js","sourceRoot":"","sources":["../src/rest.ts"],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C,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;YAC3C,MAAM,EAAE,OAAO,EAAE,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC;YAE9D,MAAM,WAAW,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,mBAAmB,CAAC,CAAC;YACvF,MAAM,UAAU,GAAG,IAAA,gBAAM,GAAE,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YAE7C,OAAO,CAAC,OAAO,KAAf,OAAO,CAAC,OAAO,GAAK,EAAE,EAAC;YACvB,OAAO,CAAC,OAAO,CAAC,QAAQ,GAAG,UAAU,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC,CAAA;AAxBY,QAAA,IAAI,QAwBhB"}
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@feathersjs/express",
3
3
  "description": "Feathers Express framework bindings and REST provider",
4
- "version": "5.0.0-pre.2",
4
+ "version": "5.0.0-pre.22",
5
5
  "homepage": "https://feathersjs.com",
6
6
  "main": "lib/",
7
+ "types": "lib/",
7
8
  "keywords": [
8
9
  "feathers",
9
10
  "feathers-plugin"
@@ -15,7 +16,8 @@
15
16
  },
16
17
  "repository": {
17
18
  "type": "git",
18
- "url": "git://github.com/feathersjs/feathers.git"
19
+ "url": "git://github.com/feathersjs/feathers.git",
20
+ "directory": "packages/express"
19
21
  },
20
22
  "author": {
21
23
  "name": "Feathers contributors",
@@ -49,26 +51,27 @@
49
51
  "access": "public"
50
52
  },
51
53
  "dependencies": {
52
- "@feathersjs/commons": "^5.0.0-pre.2",
53
- "@feathersjs/errors": "^5.0.0-pre.2",
54
- "@types/express": "^4.17.11",
55
- "debug": "^4.3.1",
56
- "express": "^4.17.1",
57
- "lodash": "^4.17.21"
54
+ "@feathersjs/authentication": "^5.0.0-pre.22",
55
+ "@feathersjs/commons": "^5.0.0-pre.22",
56
+ "@feathersjs/errors": "^5.0.0-pre.22",
57
+ "@feathersjs/feathers": "^5.0.0-pre.22",
58
+ "@feathersjs/transport-commons": "^5.0.0-pre.22",
59
+ "@types/express": "^4.17.13",
60
+ "@types/express-serve-static-core": "^4.17.28",
61
+ "express": "^4.18.1"
58
62
  },
59
63
  "devDependencies": {
60
- "@feathersjs/authentication": "^5.0.0-pre.2",
61
- "@feathersjs/authentication-local": "^5.0.0-pre.2",
62
- "@feathersjs/feathers": "^5.0.0-pre.2",
63
- "@feathersjs/tests": "^5.0.0-pre.2",
64
- "@types/mocha": "^8.2.2",
65
- "@types/node": "^14.14.37",
66
- "axios": "^0.21.1",
64
+ "@feathersjs/authentication-local": "^5.0.0-pre.22",
65
+ "@feathersjs/tests": "^5.0.0-pre.22",
66
+ "@types/lodash": "^4.14.182",
67
+ "@types/mocha": "^9.1.1",
68
+ "@types/node": "^17.0.31",
69
+ "axios": "^0.27.2",
67
70
  "lodash": "^4.17.21",
68
- "mocha": "^8.3.2",
69
- "shx": "^0.3.3",
70
- "ts-node": "^9.1.1",
71
- "typescript": "^4.2.3"
71
+ "mocha": "^10.0.0",
72
+ "shx": "^0.3.4",
73
+ "ts-node": "^10.7.0",
74
+ "typescript": "^4.6.4"
72
75
  },
73
- "gitHead": "6e1f888dc5b612d2d77653177622e3f66245a0fb"
76
+ "gitHead": "e452e02063e6d8943a9cae2315ab585bc4f82fb6"
74
77
  }
@@ -1,71 +1,61 @@
1
- import Debug from 'debug';
2
- import { merge, flatten } from 'lodash';
3
- import { NextFunction, RequestHandler } from 'express';
1
+ import { RequestHandler, Request, Response } from 'express';
2
+ import { HookContext } from '@feathersjs/feathers';
3
+ import { createDebug } from '@feathersjs/commons';
4
+ import { authenticate as AuthenticateHook } from '@feathersjs/authentication';
4
5
 
5
- const debug = Debug('@feathersjs/express/authentication');
6
+ import { Application } from './declarations';
6
7
 
7
- type StrategyOptions = {
8
- service?: string;
9
- strategies: string[]
8
+ const debug = createDebug('@feathersjs/express/authentication');
9
+
10
+ const toHandler = (func: (req: Request, res: Response, next: () => void) => Promise<void>): RequestHandler => {
11
+ return (req, res, next) => func(req, res, next).catch(error => next(error));
10
12
  };
11
13
 
12
- const normalizeStrategy = (_settings: string|StrategyOptions, ..._strategies: string[]) =>
13
- typeof _settings === 'string'
14
- ? { strategies: flatten([ _settings, ..._strategies ]) }
15
- : _settings;
14
+ export type AuthenticationSettings = {
15
+ service?: string;
16
+ strategies?: string[];
17
+ };
16
18
 
17
- export function parseAuthentication (settings: any = {}): RequestHandler {
18
- return function (req, res, next) {
19
- const app = req.app as any;
20
- const service = app.defaultAuthentication ? app.defaultAuthentication(settings.service) : null;
19
+ export function parseAuthentication (settings: AuthenticationSettings = {}): RequestHandler {
20
+ return toHandler(async (req, res, next) => {
21
+ const app = req.app as any as Application;
22
+ const service = app.defaultAuthentication?.(settings.service);
21
23
 
22
- if (service === null) {
24
+ if (!service) {
23
25
  return next();
24
26
  }
25
27
 
26
28
  const config = service.configuration;
27
- const authStrategies = config.parseStrategies || config.authStrategies || [];
29
+ const authStrategies = settings.strategies || config.parseStrategies || config.authStrategies || [];
28
30
 
29
31
  if (authStrategies.length === 0) {
30
32
  debug('No `authStrategies` or `parseStrategies` found in authentication configuration');
31
33
  return next();
32
34
  }
33
35
 
34
- service.parse(req, res, ...authStrategies)
35
- .then((authentication: any) => {
36
- if (authentication) {
37
- debug('Parsed authentication from HTTP header', authentication);
38
- merge(req, {
39
- authentication,
40
- feathers: { authentication }
41
- });
42
- }
43
-
44
- next();
45
- }).catch(next);
46
- };
47
- }
36
+ const authentication = await service.parse(req, res, ...authStrategies)
37
+
38
+ if (authentication) {
39
+ debug('Parsed authentication from HTTP header', authentication);
40
+ req.feathers = { ...req.feathers, authentication };
41
+ }
48
42
 
49
- export function authenticate (_settings: string|StrategyOptions, ..._strategies: string[]) {
50
- const settings = normalizeStrategy(_settings, ..._strategies);
43
+ return next();
44
+ });
45
+ }
51
46
 
52
- if (!Array.isArray(settings.strategies) || settings.strategies.length === 0) {
53
- throw new Error('\'authenticate\' middleware requires at least one strategy name');
54
- }
47
+ export function authenticate (settings: string | AuthenticationSettings, ...strategies: string[]): RequestHandler {
48
+ const hook = AuthenticateHook(settings, ...strategies);
55
49
 
56
- return (_req: Request, _res: Response, next: NextFunction) => {
57
- const req = _req as any;
58
- const { app, authentication } = req;
59
- const service = app.defaultAuthentication(settings.service);
50
+ return toHandler(async (req, _res, next) => {
51
+ const app = req.app as any as Application;
52
+ const params = req.feathers;
53
+ const context = { app, params } as any as HookContext;
60
54
 
61
- debug('Authenticating with Express middleware and strategies', settings.strategies);
55
+ await hook(context);
62
56
 
63
- service.authenticate(authentication, req.feathers, ...settings.strategies)
64
- .then((authResult: any) => {
65
- debug('Merging request with', authResult);
66
- merge(req, authResult);
57
+ req.feathers = context.params;
67
58
 
68
- next();
69
- }).catch(next);
70
- };
59
+ return next();
60
+ });
71
61
  }
@@ -2,59 +2,62 @@ import http from 'http';
2
2
  import express, { Express } from 'express';
3
3
  import {
4
4
  Application as FeathersApplication, Params as FeathersParams,
5
- HookContext, ServiceMethods, ServiceInterface
5
+ HookContext, ServiceMethods, ServiceInterface, RouteLookup
6
6
  } from '@feathersjs/feathers';
7
7
 
8
- interface ExpressUseHandler<T, ServiceTypes> {
9
- <L extends keyof ServiceTypes & string> (
8
+ interface ExpressUseHandler<T, Services> {
9
+ <L extends keyof Services & string> (
10
10
  path: L,
11
11
  ...middlewareOrService: (
12
- Express|express.RequestHandler|
13
- (keyof any extends keyof ServiceTypes ? ServiceInterface<any> : ServiceTypes[L])
12
+ Express|express.RequestHandler|express.RequestHandler[]|
13
+ (keyof any extends keyof Services ? ServiceInterface : Services[L])
14
14
  )[]
15
15
  ): T;
16
- (path: RegExp, ...expressHandlers: express.RequestHandler[]): T;
16
+ (path: string|RegExp, ...expressHandlers: express.RequestHandler[]): T;
17
17
  (...expressHandlers: express.RequestHandler[]): T;
18
18
  (handler: Express|express.ErrorRequestHandler): T;
19
19
  }
20
20
 
21
- export interface ExpressOverrides<ServiceTypes> {
21
+ export interface ExpressOverrides<Services> {
22
22
  listen(port: number, hostname: string, backlog: number, callback?: () => void): Promise<http.Server>;
23
23
  listen(port: number, hostname: string, callback?: () => void): Promise<http.Server>;
24
24
  listen(port: number|string|any, callback?: () => void): Promise<http.Server>;
25
25
  listen(callback?: () => void): Promise<http.Server>;
26
- use: ExpressUseHandler<this, ServiceTypes>;
26
+ use: ExpressUseHandler<this, Services>;
27
+ server: http.Server;
27
28
  }
28
29
 
29
- export type Application<ServiceTypes = any, AppSettings = any> =
30
- Omit<Express, 'listen'|'use'> &
31
- FeathersApplication<ServiceTypes, AppSettings> &
32
- ExpressOverrides<ServiceTypes>;
30
+ export type Application<Services = any, Settings = any> =
31
+ Omit<Express, 'listen'|'use'|'get'|'set'> &
32
+ FeathersApplication<Services, Settings> &
33
+ ExpressOverrides<Services>;
33
34
 
34
35
  declare module '@feathersjs/feathers/lib/declarations' {
35
- export interface ServiceOptions {
36
- middleware?: {
37
- before: express.RequestHandler[],
38
- after: express.RequestHandler[]
39
- }
36
+ interface ServiceOptions {
37
+ express?: {
38
+ before?: express.RequestHandler[];
39
+ after?: express.RequestHandler[];
40
+ composed?: express.RequestHandler;
41
+ };
40
42
  }
41
43
  }
42
44
 
43
45
  declare module 'express-serve-static-core' {
44
46
  interface Request {
45
- feathers?: Partial<FeathersParams>;
47
+ feathers?: Partial<FeathersParams> & { [key: string]: any };
48
+ lookup?: RouteLookup;
46
49
  }
47
50
 
48
51
  interface Response {
49
- data?: any;
50
- hook?: HookContext;
52
+ data?: any;
53
+ hook?: HookContext;
51
54
  }
52
55
 
53
56
  interface IRouterMatcher<T> {
54
- // eslint-disable-next-line
55
- <P extends Params = ParamsDictionary, ResBody = any, ReqBody = any>(
56
- path: PathParams,
57
- ...handlers: (RequestHandler<P, ResBody, ReqBody> | Partial<ServiceMethods<any, any>> | Application)[]
58
- ): T;
57
+ // eslint-disable-next-line
58
+ <P extends Params = ParamsDictionary, ResBody = any, ReqBody = any>(
59
+ path: PathParams,
60
+ ...handlers: (RequestHandler<P, ResBody, ReqBody> | Partial<ServiceMethods> | Application)[]
61
+ ): T;
59
62
  }
60
63
  }
package/src/handlers.ts CHANGED
@@ -18,10 +18,10 @@ export function notFound ({ verbose = false } = {}): RequestHandler {
18
18
  }
19
19
 
20
20
  export type ErrorHandlerOptions = {
21
- public?: string,
22
- logger?: boolean|{ error?: (msg: any) => void, info?: (msg: any) => void },
23
- html?: any,
24
- json?: any
21
+ public?: string;
22
+ logger?: boolean|{ error?: (msg: any) => void, info?: (msg: any) => void };
23
+ html?: any;
24
+ json?: any;
25
25
  };
26
26
 
27
27
  export function errorHandler (_options: ErrorHandlerOptions = {}): ErrorRequestHandler {