-
Notifications
You must be signed in to change notification settings - Fork 93
/
http-context.js
597 lines (525 loc) · 16.2 KB
/
http-context.js
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Copyright IBM Corp. 2013,2016. All Rights Reserved.
// Node module: strong-remoting
// This file is licensed under the Artistic License 2.0.
// License text available at https://opensource.org/licenses/Artistic-2.0
'use strict';
var g = require('strong-globalize')();
/*!
* Expose `HttpContext`.
*/
module.exports = HttpContext;
/*!
* Module dependencies.
*/
var debug = require('debug')('strong-remoting:http-context');
var util = require('util');
var inherits = util.inherits;
var assert = require('assert');
var ContextBase = require('./context-base');
var js2xmlparser = require('js2xmlparser');
var SharedMethod = require('./shared-method');
var DEFAULT_SUPPORTED_TYPES = [
'application/json', 'application/javascript', 'application/xml',
'text/javascript', 'text/xml',
'json', 'xml',
'*/*',
];
/*!
* This comment is here as a workaround for a strong-docs bug.
* The above array value leads to spurious doc output.
*/
var MuxDemux = require('mux-demux');
var SSEClient = require('sse').Client;
/**
* Create a new `HttpContext` with the given `options`.
* Invoking a remote method via HTTP creates `HttpContext` object.
*
* @param {Object} req Express Request object.
* @param {Object} res Express Response object.
* @param {Function} method A [SharedMethod](#sharedmethod)
* @options {Object} options See below.
* @property {Boolean} xml Set to `true` to enable XML-based types. Default is false.
* @class
*/
function HttpContext(req, res, method, options, typeRegistry) {
ContextBase.call(this, method, typeRegistry);
this.req = req;
this.res = res;
this.method = method;
this.options = options || {};
this.args = this.buildArgs(method);
this.methodString = method.stringName;
this.supportedTypes = this.options.supportedTypes || DEFAULT_SUPPORTED_TYPES;
this.result = {};
var streamsDesc = method.streams;
var returnStreamDesc = streamsDesc && streamsDesc.returns;
var methodReturnsStream = !!returnStreamDesc;
if (this.supportedTypes === DEFAULT_SUPPORTED_TYPES && !this.options.xml) {
// Disable all XML-based types by default
this.supportedTypes = this.supportedTypes.filter(function(type) {
return !/\bxml\b/i.test(type);
});
}
req.remotingContext = this;
// streaming support
if (methodReturnsStream) {
this.createStream();
}
}
inherits(HttpContext, ContextBase);
HttpContext.prototype.createStream = function() {
var streamsDesc = this.method.streams;
var returnStreamDesc = streamsDesc && streamsDesc.returns;
var mdm = this.muxDemuxStream = new MuxDemux();
var io = this.io = {};
var res = this.res;
debug('create stream');
if (returnStreamDesc.json && returnStreamDesc.type === 'ReadableStream') {
if (!this.shouldReturnEventStream()) {
res.setHeader('Content-Type',
returnStreamDesc.contentType || 'application/json; boundary=NL');
res.setHeader('Transfer-Encoding', 'chunked');
this.io.out = mdm.createWriteStream();
// since the method returns a ReadableStream
// setup an output to pipe the ReadableStream to
mdm.pipe(res);
}
}
};
/**
* Build args object from the http context's `req` and `res`.
*/
HttpContext.prototype.buildArgs = function(method) {
var args = {};
var ctx = this;
var accepts = method.accepts;
var isJsonRequest = /^application\/json\b/.test(ctx.req.get('content-type'));
// build arguments from req and method options
for (var i = 0, n = accepts.length; i < n; i++) {
var o = accepts[i];
var httpFormat = o.http;
var name = o.name || o.arg;
var val;
var typeConverter = ctx.typeRegistry.getConverter(o.type);
var conversionOptions = SharedMethod.getConversionOptionsForArg(o);
// Turn off sloppy coercion for values coming from JSON payloads.
// This is because JSON, unlike other methods, properly retains types
// like Numbers, Booleans, and null/undefined.
var doSloppyCoerce = !isJsonRequest;
// This is an http method keyword, which requires special parsing.
if (httpFormat) {
switch (typeof httpFormat) {
case 'function':
// the options have defined a formatter
val = httpFormat(ctx);
// it's up to the custom provider to perform any coercion as needed
doSloppyCoerce = false;
break;
case 'object':
switch (httpFormat.source) {
case 'body':
val = ctx.req.body;
break;
case 'form':
case 'formData':
// From the form (body)
val = ctx.req.body && ctx.req.body[name];
break;
case 'query':
// From the query string
val = ctx.req.query[name];
doSloppyCoerce = true;
break;
case 'path':
// From the url path
val = ctx.req.params[name];
doSloppyCoerce = true;
break;
case 'header':
val = ctx.req.get(name);
doSloppyCoerce = true;
break;
case 'req':
// Direct access to http req
val = ctx.req;
break;
case 'res':
// Direct access to http res
val = ctx.res;
break;
case 'context':
// Direct access to http context
val = ctx;
break;
}
break;
}
} else {
val = ctx.getArgByName(name, o);
doSloppyCoerce = !(isJsonRequest && ctx.req.body &&
val === ctx.req.body[name]);
}
// Most of the time, the data comes through 'sloppy' methods like HTTP headers or a qs
// which don't preserve types.
//
// Use some sloppy typing semantics to try to guess what the user meant to send.
var result = doSloppyCoerce ?
typeConverter.fromSloppyValue(ctx, val, conversionOptions) :
typeConverter.fromTypedValue(ctx, val, conversionOptions);
debug('arg %j: %s converted %j to %j',
name, doSloppyCoerce ? 'sloppy' : 'typed', val, result);
var isValidResult = typeof result === 'object' &&
('error' in result || 'value' in result);
if (!isValidResult) {
throw new (assert.AssertionError)({
message: 'Type conversion result should have "error" or "value" property. ' +
'Got ' + JSON.stringify(result) + ' instead.',
});
}
if (result.error) {
throw result.error;
}
// Set the argument value.
args[o.arg] = result.value;
}
return args;
};
/**
* Get an arg by name using the given options.
*
* @param {String} name
* @param {Object} options **optional**
*/
HttpContext.prototype.getArgByName = function(name, options) {
var req = this.req;
// search these in order by name
var arg = req.params[name] !== undefined ? req.params[name] : // params
(req.body && req.body[name]) !== undefined ? req.body[name] : // body
req.query[name] !== undefined ? req.query[name] : // query
req.get(name); // header
return arg;
};
function buildArgs(ctx, method, fn) {
try {
return ctx.buildArgs(method);
} catch (err) {
// JSON.parse() might throw
process.nextTick(function() {
fn(err);
});
return undefined;
}
}
/**
* Invoke the given shared method using the provided scope against the current context.
*/
HttpContext.prototype.invoke = function(scope, method, fn, isCtor) {
var args = this.args;
if (isCtor) {
args = this.ctorArgs = buildArgs(this, method, fn);
if (args === undefined) {
return;
}
}
var http = method.http;
var pipe = http && http.pipe;
var pipeDest = pipe && pipe.dest;
var pipeSrc = pipe && pipe.source;
var ctx = this;
var defaultErrorStatus = http && http.errorStatus;
var res = this.res;
if (pipeDest) {
// only support response for now
switch (pipeDest) {
case 'res':
// Probably not correct...but passes my test.
this.res.header('Content-Type', 'application/json');
this.res.header('Transfer-Encoding', 'chunked');
var stream = method.invoke(scope, args, this.options, ctx, fn);
stream.pipe(this.res);
break;
default:
fn(new Error(g.f('unsupported pipe destination')));
break;
}
} else if (pipeSrc) {
// only support request for now
switch (pipeDest) {
case 'req':
this.req.pipe(method.invoke(scope, args, this.options, ctx, fn));
break;
default:
fn(new Error(g.f('unsupported pipe source')));
break;
}
} else {
// simple invoke
method.invoke(scope, args, this.options, ctx, function(err, result) {
if (err) {
if (defaultErrorStatus &&
(res.statusCode === undefined || res.statusCode === 200)) {
res.status(err.status || err.statusCode || defaultErrorStatus);
}
return fn(err);
}
fn(null, result);
});
}
};
HttpContext.prototype.setReturnArgByName = function(name, value) {
var ARG_WAS_HANDLED = true;
var returnDesc = this.method.getReturnArgDescByName(name);
var result = this.result;
var res = this.res;
if (!returnDesc) {
debug('warning: cannot set return value for arg' +
' (%s) without description!', name);
return;
}
if (returnDesc.root) {
// TODO(bajtos) call SharedMethod's convertToBasicRemotingType here?
this.resultType = typeof returnDesc.type === 'string' ?
returnDesc.type.toLowerCase() : returnDesc.type;
return;
}
if (returnDesc.http) {
switch (returnDesc.http.target) {
case 'status':
res.status(value);
return ARG_WAS_HANDLED;
case 'header':
res.set(returnDesc.http.header || name, value);
return ARG_WAS_HANDLED;
}
}
};
function toJSON(input) {
if (!input) {
return input;
}
if (typeof input.toJSON === 'function') {
return input.toJSON();
} else if (Array.isArray(input)) {
return input.map(toJSON);
} else {
return input;
}
}
function toXML(input, options) {
var xml;
var xmlDefaultOptions = {declaration: true};
var xmlOptions = util._extend(xmlDefaultOptions, options);
if (input && typeof input.toXML === 'function') {
xml = input.toXML();
} else {
if (typeof input == 'object') {
// Trigger toJSON() conversions
input = toJSON(input);
}
if (Array.isArray(input)) {
input = {result: input};
}
xml = js2xmlparser.parse(xmlOptions.wrapperElement || 'response', input, {
declaration: {
include: xmlOptions.declaration,
encoding: 'UTF-8',
},
format: {
doubleQuotes: true,
indent: ' ',
},
convertMap: {
'[object Date]': function(date) {
return date.toISOString();
},
},
});
}
return xml;
}
HttpContext.prototype.shouldReturnEventStream = function() {
var req = this.req;
var query = req.query;
var format = query._format;
var acceptable = req.accepts('text/event-stream');
var returnEventStream = (format === 'event-stream') || acceptable;
if (returnEventStream) {
this.res.setHeader('Content-Encoding', 'x-no-compression');
}
return returnEventStream;
};
HttpContext.prototype.respondWithEventStream = function(stream) {
var client = new SSEClient(this.req, this.res);
client.initialize();
stream.on('data', function(chunk) {
client.send('data', JSON.stringify(chunk));
});
stream.on('error', function(err) {
var outErr = {message: err.message};
for (var key in err) {
outErr[key] = err[key];
}
client.send('error', JSON.stringify(outErr));
});
stream.on('end', function() {
client.send({event: 'end', data: 'null'});
});
if (stream.destroy) {
// ReadableStream#destroy() was added in Node.js 8.0.0
// In earlier versions, some kinds of streams are already
// providing this method, which allows us to correctly cancel them.
// For streams that do not provide this method, there
// is no other reliable way for closing them prematurely.
client.once('close', function() {
stream.destroy();
});
}
};
/**
* Utility functions to send response body
*/
function sendBodyJson(res, data) {
res.json(data);
}
function sendBodyJsonp(res, data) {
res.jsonp(data);
}
function sendBodyXml(res, data, method) {
if (data === null) {
res.header('Content-Length', '7');
res.send('<null/>');
} else if (data) {
try {
var xmlOptions = method.returns[0].xml || {};
var xml = toXML(data, xmlOptions);
res.send(xml);
} catch (e) {
res.status(500).send(e + '\n' + data);
}
}
}
function sendBodyDefault(res) {
res.status(406).send('Not Acceptable');
}
/**
* Deciding on the operation of response, function is called inside this.done()
*/
HttpContext.prototype.resolveReponseOperation = function(accepts) {
var result = { // default
sendBody: sendBodyJson,
contentType: 'application/json',
};
switch (accepts) {
case '*/*':
case 'application/json':
case 'json':
break;
case 'application/vnd.api+json':
result.contentType = 'application/vnd.api+json';
break;
case 'application/javascript':
case 'text/javascript':
result.sendBody = sendBodyJsonp;
break;
case 'application/xml':
case 'text/xml':
case 'xml':
if (accepts == 'application/xml') {
result.contentType = 'application/xml';
} else {
result.contentType = 'text/xml';
}
result.sendBody = sendBodyXml;
break;
default:
result.sendBody = sendBodyDefault;
result.contentType = 'text/plain';
break;
}
return result;
};
/**
* Finish the request and send the correct response.
*/
HttpContext.prototype.done = function(cb) {
var ctx = this;
var method = this.method;
var streamsDesc = method.streams;
var returnStreamDesc = streamsDesc && streamsDesc.returns;
var methodReturnsStream = !!returnStreamDesc;
var res = this.res;
var out = this.io && this.io.out;
var err = this.error;
var result = this.result;
if (methodReturnsStream) {
if (returnStreamDesc.json) {
debug('handling json stream');
var stream = result[returnStreamDesc.arg];
if (returnStreamDesc.type === 'ReadableStream') {
if (ctx.shouldReturnEventStream()) {
debug('respondWithEventStream');
ctx.respondWithEventStream(stream);
return;
}
debug('piping to mdm stream');
stream.pipe(out);
stream.on('error', function(err) {
var outErr = {message: err.message};
for (var key in err) {
outErr[key] = err[key];
}
// this is the reason we are using mux-demux
out.error(outErr);
out.end();
});
// TODO(ritch) support multi-part streams
} else {
cb(new Error(g.f('unsupported stream type: %s', returnStreamDesc.type)));
}
} else {
cb(new Error(g.f('Unsupported stream descriptor, only descriptors ' +
'with property "{{json:true}}" are supported')));
}
return;
}
// send the result back as
// the requested content type
var data = this.result;
var accepts = this.req.accepts(this.supportedTypes);
var defaultStatus = this.method.http.status;
if (defaultStatus) {
res.status(defaultStatus);
}
if (this.req.query._format) {
if (typeof this.req.query._format !== 'string') {
accepts = 'invalid'; // this will 406
} else {
accepts = this.req.query._format.toLowerCase();
}
}
var dataExists = typeof data !== 'undefined';
var operationResults = this.resolveReponseOperation(accepts);
if (res.statusCode !== 304 && !res.get('Content-Type')) {
res.header('Content-Type', operationResults.contentType);
}
if (dataExists) {
if (this.resultType !== 'file') {
operationResults.sendBody(res, data, method);
res.end();
} else if (Buffer.isBuffer(data) || typeof(data) === 'string') {
res.end(data);
} else if (data.pipe) {
data.pipe(res);
} else {
var valueType = SharedMethod.getType(data);
var msg = g.f('Cannot create a file response from %s ', valueType);
return cb(new Error(msg));
}
} else {
if (res.statusCode === undefined || res.statusCode === 200) {
res.statusCode = 204;
}
res.end();
}
cb();
};