-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathhttp-handler.integration.ts
537 lines (463 loc) · 14.1 KB
/
http-handler.integration.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/rest
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {
HttpHandler,
DefaultSequence,
ServerRequest,
writeResultToResponse,
parseOperationArgs,
RestBindings,
FindRouteProvider,
InvokeMethodProvider,
RejectProvider,
} from '../..';
import {ControllerSpec, get} from '@loopback/openapi-v2';
import {Context} from '@loopback/context';
import {Client, createClientForHandler} from '@loopback/testlab';
import * as HttpErrors from 'http-errors';
import * as debugModule from 'debug';
import {ParameterObject} from '@loopback/openapi-spec';
import {anOpenApiSpec, anOperationSpec} from '@loopback/openapi-spec-builder';
const debug = debugModule('loopback:rest:test');
const SequenceActions = RestBindings.SequenceActions;
describe('HttpHandler', () => {
let client: Client;
beforeEach(givenHandler);
beforeEach(givenClient);
context('with a simple HelloWorld controller', () => {
beforeEach(function setupHelloController() {
const spec = anOpenApiSpec()
.withOperationReturningString('get', '/hello', 'greet')
.build();
class HelloController {
public async greet(): Promise<string> {
return 'Hello world!';
}
}
givenControllerClass(HelloController, spec);
});
it('handles simple "GET /hello" requests', () => {
return client
.get('/hello')
.expect(200)
.expect('content-type', 'text/plain')
.expect('Hello world!');
});
});
context('with a controller with operations at different paths/verbs', () => {
beforeEach(function setupHelloController() {
const spec = anOpenApiSpec()
.withOperationReturningString('get', '/hello', 'hello')
.withOperationReturningString('get', '/bye', 'bye')
.withOperationReturningString('post', '/hello', 'postHello')
.build();
class HelloController {
public async hello(): Promise<string> {
return 'hello';
}
public async bye(): Promise<string> {
return 'bye';
}
public async postHello(): Promise<string> {
return 'hello posted';
}
}
givenControllerClass(HelloController, spec);
});
it('executes hello() for "GET /hello"', () => {
return client.get('/hello').expect('hello');
});
it('executes bye() for "GET /bye"', () => {
return client.get('/bye').expect('bye');
});
it('executes postHello() for "POST /hello', () => {
return client.post('/hello').expect('hello posted');
});
it('returns 404 for path not handled', () => {
logErrorsExcept(404);
return client.get('/unknown-path').expect(404);
});
it('returns 404 for verb not handled', () => {
logErrorsExcept(404);
return client.post('/bye').expect(404);
});
});
context('with an operation echoing a string parameter from query', () => {
beforeEach(function setupEchoController() {
const spec = anOpenApiSpec()
.withOperation('get', '/echo', {
'x-operation-name': 'echo',
parameters: [
// the type cast is not required, but improves Intellisense
<ParameterObject>{
name: 'msg',
in: 'query',
type: 'string',
},
],
responses: {
'200': {
schema: {
type: 'string',
},
description: '',
},
},
})
.build();
class EchoController {
public async echo(msg: string): Promise<string> {
return msg;
}
}
givenControllerClass(EchoController, spec);
});
it('returns "hello" for "?msg=hello"', () => {
return client.get('/echo?msg=hello').expect('hello');
});
it('url-decodes the parameter value', () => {
return client.get('/echo?msg=hello%20world').expect('hello world');
});
it('ignores other query fields', () => {
return client.get('/echo?msg=hello&ignoreKey=ignoreMe').expect('hello');
});
});
context('with a path-parameter route', () => {
beforeEach(givenRouteParamController);
it('returns "admin" for "/users/admin"', () => {
return client.get('/users/admin').expect('admin');
});
function givenRouteParamController() {
const spec = anOpenApiSpec()
.withOperation('get', '/users/{username}', {
'x-operation-name': 'getUserByUsername',
parameters: [
<ParameterObject>{
name: 'username',
in: 'path',
description: 'The name of the user to look up.',
required: true,
type: 'string',
},
],
responses: {
200: {
schema: {
type: 'string',
},
description: '',
},
},
})
.build();
class RouteParamController {
public async getUserByUsername(userName: string): Promise<string> {
return userName;
}
}
givenControllerClass(RouteParamController, spec);
}
});
context('with a header-parameter route', () => {
beforeEach(givenHeaderParamController);
it('returns the value sent in the header', () => {
return client
.get('/show-authorization')
.set('authorization', 'admin')
.expect('admin');
});
function givenHeaderParamController() {
const spec = anOpenApiSpec()
.withOperation('get', '/show-authorization', {
'x-operation-name': 'showAuthorization',
parameters: [
<ParameterObject>{
name: 'Authorization',
in: 'header',
description: 'Authorization credentials.',
required: true,
type: 'string',
},
],
responses: {
200: {
schema: {
type: 'string',
},
description: '',
},
},
})
.build();
class RouteParamController {
async showAuthorization(auth: string): Promise<string> {
return auth;
}
}
givenControllerClass(RouteParamController, spec);
}
});
context('with a formData-parameter route', () => {
beforeEach(givenFormDataParamController);
it('returns the value sent in json-encoded body', () => {
return client
.post('/show-formdata')
.send({key: 'value'})
.expect(200, 'value');
});
it('rejects url-encoded request body', () => {
logErrorsExcept(415);
return client
.post('/show-formdata')
.send('key=value')
.expect(415);
});
it('returns 400 for malformed JSON body', () => {
logErrorsExcept(400);
return client
.post('/show-formdata')
.set('content-type', 'application/json')
.send('malformed-json')
.expect(400);
});
function givenFormDataParamController() {
const spec = anOpenApiSpec()
.withOperation('post', '/show-formdata', {
'x-operation-name': 'showFormData',
parameters: [
<ParameterObject>{
name: 'key',
in: 'formData',
description: 'Any value.',
required: true,
type: 'string',
},
],
responses: {
200: {
schema: {
type: 'string',
},
description: '',
},
},
})
.build();
class RouteParamController {
async showFormData(key: string): Promise<string> {
return key;
}
}
givenControllerClass(RouteParamController, spec);
}
});
context('with a body-parameter route', () => {
beforeEach(givenBodyParamController);
it('returns the value sent in json-encoded body', () => {
return client
.post('/show-body')
.send({key: 'value'})
.expect(200, {key: 'value'});
});
it('rejects url-encoded request body', () => {
logErrorsExcept(415);
return client
.post('/show-body')
.send('key=value')
.expect(415, {
message:
'Content-type application/x-www-form-urlencoded is not supported.',
statusCode: 415,
});
});
it('returns 400 for malformed JSON body', () => {
logErrorsExcept(400);
return client
.post('/show-body')
.set('content-type', 'application/json')
.send('malformed-json')
.expect(400, {statusCode: 400});
});
function givenBodyParamController() {
const spec = anOpenApiSpec()
.withOperation('post', '/show-body', {
'x-operation-name': 'showBody',
parameters: [
<ParameterObject>{
name: 'data',
in: 'body',
description: 'Any object value.',
required: true,
schema: {type: 'object'},
},
],
responses: {
200: {
schema: {
type: 'object',
},
description: '',
},
},
})
.build();
class RouteParamController {
async showBody(data: Object): Promise<Object> {
return data;
}
}
givenControllerClass(RouteParamController, spec);
}
});
context('response serialization', () => {
it('converts object result to a JSON response', () => {
const spec = anOpenApiSpec()
.withOperation('get', '/object', {
'x-operation-name': 'getObject',
responses: {
'200': {schema: {type: 'object'}, description: ''},
},
})
.build();
class TestController {
public async getObject(): Promise<Object> {
return {key: 'value'};
}
}
givenControllerClass(TestController, spec);
return client
.get('/object')
.expect(200)
.expect('content-type', /^application\/json($|;)/)
.expect('{"key":"value"}');
});
});
context('error handling', () => {
it('handles errors throws by controller constructor', () => {
const spec = anOpenApiSpec()
.withOperationReturningString('get', '/hello', 'greet')
.build();
class ThrowingController {
constructor() {
throw new Error('Thrown from constructor.');
}
}
givenControllerClass(ThrowingController, spec);
logErrorsExcept(500);
return client.get('/hello').expect(500, {
statusCode: 500,
});
});
it('handles invocation of an unknown method', async () => {
const spec = anOpenApiSpec()
.withOperation(
'get',
'/hello',
anOperationSpec().withOperationName('unknownMethod'),
)
.build();
class TestController {}
givenControllerClass(TestController, spec);
logErrorsExcept(404);
await client.get('/hello').expect(404, {
message: 'Controller method not found: TestController.unknownMethod',
statusCode: 404,
});
});
it('handles errors thrown from the method', async () => {
const spec = anOpenApiSpec()
.withOperation(
'get',
'/hello',
anOperationSpec().withOperationName('hello'),
)
.build();
class TestController {
@get('/hello')
hello() {
const err = new HttpErrors.BadRequest('Bad hello');
err.headers = {'X-BAD-REQ': 'hello'};
throw err;
}
}
givenControllerClass(TestController, spec);
logErrorsExcept(400);
await client
.get('/hello')
.expect('X-BAD-REQ', 'hello')
.expect(400, {
message: 'Bad hello',
statusCode: 400,
});
});
it('handles 500 error thrown from the method', async () => {
const spec = anOpenApiSpec()
.withOperation(
'get',
'/hello',
anOperationSpec().withOperationName('hello'),
)
.build();
class TestController {
@get('/hello')
hello() {
throw new HttpErrors.InternalServerError('Bad hello');
}
}
givenControllerClass(TestController, spec);
logErrorsExcept(400);
await client.get('/hello').expect(500, {
statusCode: 500,
});
});
});
let rootContext: Context;
let handler: HttpHandler;
function givenHandler() {
rootContext = new Context();
rootContext.bind(SequenceActions.FIND_ROUTE).toProvider(FindRouteProvider);
rootContext.bind(SequenceActions.PARSE_PARAMS).to(parseOperationArgs);
rootContext
.bind(SequenceActions.INVOKE_METHOD)
.toProvider(InvokeMethodProvider);
rootContext.bind(SequenceActions.LOG_ERROR).to(logger);
rootContext.bind(SequenceActions.SEND).to(writeResultToResponse);
rootContext.bind(SequenceActions.REJECT).toProvider(RejectProvider);
rootContext.bind(RestBindings.SEQUENCE).toClass(DefaultSequence);
handler = new HttpHandler(rootContext);
rootContext.bind(RestBindings.HANDLER).to(handler);
}
let skipStatusCode = 200;
function logger(err: Error, statusCode: number, req: ServerRequest) {
if (statusCode === skipStatusCode) return;
debug(
'Unhandled error in %s %s: %s %s',
req.method,
req.url,
statusCode,
err.stack || err,
);
}
function logErrorsExcept(ignoreStatusCode: number) {
skipStatusCode = ignoreStatusCode;
}
function givenControllerClass(
// tslint:disable-next-line:no-any
ctor: new (...args: any[]) => Object,
spec: ControllerSpec,
) {
handler.registerController(ctor, spec);
}
function givenClient() {
client = createClientForHandler((req, res) => {
handler.handleRequest(req, res).catch(err => {
debug('Request failed.', err.stack);
if (res.headersSent) return;
res.statusCode = 500;
res.end();
});
});
}
});