-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.d.ts
235 lines (214 loc) · 6.6 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
declare module "@luxuryescapes/router" {
import { Request as ExpressRequest, Response, Express, NextFunction } from "express";
import { Matcher } from "@luxuryescapes/strummer"
import { ParamsDictionary, RequestHandler as ExpressHandler } from 'express-serve-static-core';
import { ParsedQs } from "qs";
import { API } from "@luxuryescapes/lib-types";
export function errorHandler(
err: Error,
req: ExpressRequest,
res: Response,
next: NextFunction
): void;
export function generateTypes(
mount: (server: Express) => RouterAbstraction,
path: string
): Promise<void>;
interface Logger {
debug: Function;
log: Function;
warn: Function;
error: Function;
}
/**
* New AWS environment has 3 environments:
* - dev
* - staging
* - prod
*
* 'development' can be used for local development, 'spec' for unit tests and 'test' and 'production' are being deprecated.
*/
export type AppEnv = 'dev' | 'development' | 'spec' | 'test' | 'staging' | 'prod' | 'production';
interface SentryConfig {
appEnv: AppEnv;
sentryDSN?: string;
logger?: Logger;
}
interface RouterConfig {
validateResponses?: boolean;
logRequests?: boolean;
logResponses?: boolean;
correlationIdExtractor?: (req: ExpressRequest, res: Response) => string;
logger?: Logger;
sentryDSN?: string;
appEnv?: AppEnv;
swaggerBaseProperties?: {
info: {
description: string;
version: string;
title: string;
termsOfService: string | null;
contact: {
email: string;
};
};
host: string;
basePath: string;
tags: string[];
consumes: string[];
produces: string[];
schemes: string[];
paths: object;
securityDefinitions: object;
definitions: object;
preHandlers?: ExpressHandler[];
};
sanitizeKeys?: Array<string | RegExp>;
}
interface RouteSchema {
request: {
query?: Matcher;
params?: Matcher;
body?: Matcher;
};
responses: Record<number, Matcher>
}
interface RouteOptions {
/**
* Path for the route
* @see https://expressjs.com/en/4x/api.html#path-examples
*/
url: string;
/** The route will be referenced by this ID in the contract */
operationId?: string;
/** Request and response schemas. The endpoint will use these to validate incoming requests and outgoing responses. */
schema?: RouteSchema;
/**
* If `false`, the Swagger docs will specify that a cookie containing an access token is required.
* @defaultValue `false`
*/
isPublic?: boolean;
/** Pre-handlers are run before request validation. Usually used for authentication. */
preHandlers?: ExpressHandler[];
/** Handlers are run after request validation. */
handlers: ((req: any, res: Response, next: NextFunction) => void)[]
/** For Swagger docs */
tags?: string[];
/** For Swagger docs */
summary?: string;
/** For Swagger docs */
description?: string;
/** For Swagger docs */
deprecated?: boolean;
/**
* If `true`, logs a warning on request validation error.
* @defaultValue `false`
*/
warnOnRequestValidationError?: boolean;
/**
* Options to be passed to `express.json()`
* @see https://expressjs.com/en/4x/api.html#express.json
* @defaultValue `{}`
*/
jsonOptions?: { [option: string]: string | number | boolean | null | undefined };
}
interface SchemaRouteOptions {
url: string;
schema: object;
}
type OpenAPISpec = Record<string, any>;
export interface RouterAbstraction {
serveSwagger: (path: string) => void;
app: Express,
options: (options: RouteOptions) => void;
get: (options: RouteOptions) => void;
post: (options: RouteOptions) => void;
put: (options: RouteOptions) => void;
delete: (options: RouteOptions) => void;
patch: (options: RouteOptions) => void;
schema: (options: SchemaRouteOptions) => void;
toSwagger: () => OpenAPISpec;
useErrorHandler: () => void;
}
export function router(app: Express, config: RouterConfig): RouterAbstraction;
export function initializeSentry(config: SentryConfig): boolean;
interface HTTPError extends Error {
new (code: number, message: string, errors?: (string | object)[], refCode?: string) : HTTPError
code: number
errors: (string | object)[]
refCode: string
responseJson: object
}
interface InheritedHTTPError {
new (message: string, errors?: (string | object)[]) : HTTPError
code: number
errors: (string | object)[]
responseJson: object
}
interface errors {
HTTPError: HTTPError,
ForbiddenError: InheritedHTTPError,
UnauthorizedError: InheritedHTTPError,
InvalidRequestError: InheritedHTTPError,
NotFoundError: InheritedHTTPError,
ServerError: InheritedHTTPError,
ServiceUnavailableError: InheritedHTTPError,
UnprocessableEntityError: InheritedHTTPError
}
export const errors: errors
interface Schema<T> {
content: {
"application/json": T;
};
}
type ResBody<
operations extends Record<string, any>,
O extends keyof operations,
Response = operations[O]["responses"]
> = Response[keyof Response] extends Schema<infer S> ? S : never;
type Jwt = {
sub: string
jti: string,
iat: number,
iss: string,
exp: number,
sut: boolean,
roles: string[],
aud?: string
}
interface AuthenticatedRequest<P = ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = ParsedQs>
extends ExpressRequest<P, ResBody, ReqBody, ReqQuery> {
jwt: Jwt;
user: { // verifyUserSignature only sets jwt, but most auth checks use verifyUser which sets the user object as well.
id_member: API.Auth.User['id_member']
roles: API.Auth.User['roles']
}
}
export interface Handler<
operations extends Record<string, any>,
O extends keyof operations,
R = ResBody<operations, O>,
parameters = operations[O]["parameters"],
PathParams = parameters extends { path: any }
? parameters["path"]
: {},
ReqBody = parameters extends { body: { payload: any } }
? parameters["body"]["payload"]
: {},
Query = parameters extends { query: any }
? parameters["query"]
: {},
Header = parameters extends { header: any }
? parameters['header']
: {},
Request = Header extends { Cookie: any } ?
AuthenticatedRequest<PathParams, R, ReqBody, Query> :
ExpressRequest<PathParams, R, ReqBody, Query>
> {
(
req: Request,
res: Response<R>,
next: NextFunction
): void | Promise<void>;
}
}