UNPKG

6.42 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/rest
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import {HandlerContext, Request, Response} from '@loopback/express';
7import {ReferenceObject, SchemaObject} from '@loopback/openapi-v3';
8import Ajv, {
9 ErrorObject,
10 FormatDefinition,
11 KeywordDefinition,
12 Options as AjvOptions,
13 ValidateFunction,
14} from 'ajv';
15import {ErrorMessageOptions} from 'ajv-errors';
16import {
17 Options,
18 OptionsJson,
19 OptionsText,
20 OptionsUrlencoded,
21} from 'body-parser';
22import {ResolvedRoute, RouteEntry} from './router';
23
24/**
25 * Re-export types from `./middleware`
26 */
27export * from '@loopback/express';
28
29/**
30 * Find a route matching the incoming request.
31 * Throw an error when no route was found.
32 */
33export type FindRoute = (request: Request) => ResolvedRoute;
34
35/**
36 * A function to parse OpenAPI operation parameters for a given route
37 */
38export type ParseParams = (
39 request: Request,
40 route: ResolvedRoute,
41) => Promise<OperationArgs>;
42
43/**
44 * Invokes a method defined in the Application Controller
45 *
46 * @param controller - Name of end-user's application controller
47 * class which defines the methods.
48 * @param method - Method name in application controller class
49 * @param args - Operation arguments for the method
50 * @returns OperationRetval Result from method invocation
51 */
52export type InvokeMethod = (
53 route: RouteEntry,
54 args: OperationArgs,
55) => Promise<OperationRetval>;
56
57/**
58 * Send the operation response back to the client.
59 *
60 * @param response - The response the response to send to.
61 * @param result - The operation result to send.
62 */
63export type Send = (response: Response, result: OperationRetval) => void;
64
65/**
66 * Reject the request with an error.
67 *
68 * @param handlerContext - The context object holding HTTP request, response
69 * and other data needed to handle an incoming HTTP request.
70 * @param err - The error.
71 */
72export type Reject = (handlerContext: HandlerContext, err: Error) => void;
73
74/**
75 * Log information about a failed request.
76 *
77 * @param err - The error reported by request handling code.
78 * @param statusCode - Status code of the HTTP response
79 * @param request - The request that failed.
80 */
81export type LogError = (
82 err: Error,
83 statusCode: number,
84 request: Request,
85) => void;
86
87/**
88 * Cache for AJV schema validators
89 */
90export type SchemaValidatorCache = WeakMap<
91 SchemaObject | ReferenceObject, // First keyed by schema object
92 Map<string, ValidateFunction> // Second level keyed by stringified AJV options
93>;
94
95/**
96 * Options for AJV errors
97 */
98export type AjvErrorOptions = ErrorMessageOptions;
99
100/**
101 * Factory function for Ajv instances
102 */
103export type AjvFactory = (options?: AjvOptions) => Ajv;
104
105/**
106 * Ajv keyword definition with a name
107 */
108export type AjvKeyword = KeywordDefinition;
109
110/**
111 * Ajv format definition with a name
112 */
113export type AjvFormat<T extends string | number = string> =
114 FormatDefinition<T> & {name: string};
115
116/**
117 * Options for any value validation using AJV
118 */
119export interface ValueValidationOptions extends ValidationOptions {
120 /**
121 * Where the data comes from. It can be 'body', 'path', 'header',
122 * 'query', 'cookie', etc...
123 */
124 source?: string;
125
126 /**
127 * Parameter name, as provided in `ParameterObject#name` property.
128 */
129 name?: string;
130}
131
132/**
133 * Options for request body validation using AJV
134 */
135export interface ValidationOptions extends AjvOptions {
136 /**
137 * Custom cache for compiled schemas by AJV. This setting makes it possible
138 * to skip the default cache.
139 */
140 compiledSchemaCache?: SchemaValidatorCache;
141 /**
142 * Enable additional AJV keywords from https://github.com/epoberezkin/ajv-keywords
143 * - `string[]`: Add an array of keywords from `ajv-keywords`
144 */
145 ajvKeywords?: string[];
146 /**
147 * Enable custom error messages in JSON-Schema for AJV validator
148 * from https://github.com/epoberezkin/ajv-errors
149 * - `true`: Enable `ajv-errors`
150 * - `AjvErrorOptions`: Enable `ajv-errors` with options
151 */
152 ajvErrors?: AjvErrorOptions;
153 /**
154 * A function that transform the `ErrorObject`s reported by AJV.
155 * This could be used for error messages customization, localization, etc.
156 */
157 ajvErrorTransformer?: (errors: ErrorObject[]) => ErrorObject[];
158
159 /**
160 * A factory to create Ajv instance
161 */
162 ajvFactory?: (options: AjvOptions) => Ajv;
163
164 /**
165 * An array of keys to be rejected, such as `__proto__`.
166 */
167 prohibitedKeys?: string[];
168}
169
170/* eslint-disable @typescript-eslint/no-explicit-any */
171
172/**
173 * Options for request body parsing
174 * See https://github.com/expressjs/body-parser/#options
175 *
176 * Built-in parsers retrieve their own options from the request body parser
177 * options. The parser specific properties override common ones.
178 */
179export interface RequestBodyParserOptions extends Options {
180 /**
181 * Options for json parser
182 */
183 json?: OptionsJson;
184 /**
185 * Options for urlencoded parser
186 */
187 urlencoded?: OptionsUrlencoded;
188 /**
189 * Options for text parser
190 */
191 text?: OptionsText;
192 /**
193 * Options for raw parser
194 */
195 raw?: Options;
196 /**
197 * Validation options for AJV, see https://github.com/epoberezkin/ajv#options
198 * This setting is global for all request body parsers and it cannot be
199 * overridden inside parser specific properties such as `json` or `text`.
200 */
201 validation?: ValidationOptions;
202 /**
203 * Common options for all parsers
204 */
205 [name: string]: unknown;
206}
207
208export type PathParameterValues = {[key: string]: any};
209export type OperationArgs = any[];
210
211/**
212 * Return value of a controller method (a function implementing an operation).
213 * This is a type alias for "any", used to distinguish
214 * operation results from other "any" typed values.
215 */
216export type OperationRetval = any;
217
218/**
219 * user profile to add in session
220 */
221export interface SessionUserProfile {
222 provider: string;
223 token: string;
224 email: string;
225 [attribute: string]: any;
226}
227
228/**
229 * interface to set variables in user session
230 */
231export interface Session {
232 profile: SessionUserProfile;
233 [key: string]: any;
234}
235
236/**
237 * extending express request type with a session field
238 */
239export interface RequestWithSession extends Request {
240 session: Session;
241}
242
243// For backwards compatibility
244// TODO(SEMVER-MAJOR)
245export type RequestBodyValidationOptions = ValidationOptions;