forked from tedeh/jayson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.ts
778 lines (612 loc) · 19.8 KB
/
test.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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
import * as jayson from './..';
import * as jaysonPromise from './../promise';
import jaysonBrowserClient from './../lib/client/browser';
import jaysonPromiseBrowserClient from './../promise/lib/client/browser';
import { reduce, isArray } from 'lodash';
import { Express } from 'express-serve-static-core';
/**
* This file contains tests for the typescript type definitions.
* Most of them are based on the examples files.
*/
export function test_example_1() {
var jsonParser = require('body-parser').json;
var connect = require('connect');
var app = connect();
var server = new jayson.Server({
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
// parse request body before the jayson middleware
app.use(jsonParser());
app.use(server.middleware());
app.listen(3000);
}
export function test_example_2() {
var server = new jayson.Server({
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
var client = new jayson.Client(server);
var batch = [
client.request('does_not_exist', [10, 5]),
client.request('add', [1, 1]),
client.request('add', [0, 0], null) // a notification
];
client.request(batch, function(err:any, errors:any, successes:any) {
if(err) throw err;
console.log('errors', errors); // array of requests that errored
console.log('successes', successes); // array of requests that succeeded
});
client.request(batch, function(err:any, responses:any) {
if(err) throw err;
console.log('responses', responses); // all responses together
});
}
export function test_example_3() {
var client = jayson.Client.https({
port: 3000
});
client.request('multiply', [5, 5], function(err, error, result) {
if(err) throw err;
console.log(result); // 25
});
}
export function test_example_4() {
var server = new jayson.Server({
multiply: function(args:any, callback:any) {
callback(null, args[0] * args[1]);
}
});
server.https().listen(3000, function() {
console.log('Server listening on http://localhost:3000');
});
}
export function test_example_5() {
var fs = require('fs');
var path = require('path');
var options = {
port: 3000,
host: 'localhost'
};
// create a client
var client = jayson.Client.tcp(options);
// invoke "add"
client.request('add', [1, 1], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 2
});
}
export function test_example_6() {
var fs = require('fs');
var path = require('path');
var options = {
};
// create a server
var server = new jayson.Server({
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
// Bind a http interface to the server and let it listen to localhost:3000
server.tcp(options).listen(3000);
}
export function test_example_7() {
var client = jayson.Client.http({
port: 3000
});
client.request('multiply', [5, 5], function(err:any, error:any, result:any) {
if(err) throw err;
console.log(result); // 25
});
}
export function test_example_8() {
var server = new jayson.Server({
multiply: function(args:any, callback:any) {
callback(null, args[0] * args[1]);
}
});
server.http().listen(3000, function() {
console.log('Server listening on http://localhost:3000');
});
}
export function test_example_9() {
var client = jaysonPromise.Client.http({
port: 3000
});
var batch = [
client.request('add', [1, 2, 3, 4, 5], undefined, false),
client.request('add', [5, 6, 7, 8, 9], undefined, false),
];
client.request(batch).then(function(responses) {
console.log(responses[0].result); // 15
console.log(responses[1].result); // 35
});
}
export function test_example_10() {
var server = new jayson.Server({
add: function(args:any) {
return new Promise(function(resolve, reject) {
var sum = reduce(args, function(sum:number, value:number) { return sum + value; }, 0);
resolve(sum);
});
}
});
server.http().listen(3000);
}
export function test_example_11() {
var server = new jayson.Server();
// "http" will be an instance of require('http').Server
var http = server.http();
// "https" will be an instance of require('https').Server
var https = server.https({
//cert: require('fs').readFileSync('cert.pem'),
//key require('fs').readFileSync('key.pem')
});
http.listen(80, function() {
console.log('Listening on *:80');
});
https.listen(443, function() {
console.log('Listening on *:443');
});
}
export function test_example_12() {
var client = jayson.Client.http({
port: 3000
});
client.request('add', {b: 1, a: 2}, function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 3!
});
}
export function test_example_13() {
var server = new jayson.Server({
add: function(a:any, b:any, callback:any) {
callback(null, a + b);
}
}, {
});
server.http().listen(3000);
}
export function test_example_14() {
// create a client
var client = jayson.Client.http({
port: 3000
});
// invoke "add"
client.request('add', [1, 1], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 2
});
}
export function test_example_15() {
// create a server
var server = new jayson.Server({
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
server.http().listen(3000);
}
export function test_example_16() {
var client = jayson.Client.http({
port: 3000
});
// invoke "sumCollect" with array
client.request('sumCollect', [3, 5, 9, 11], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 28
});
// invoke "sumCollect" with object
client.request('sumCollect', {a: 2, b: 3, c: 4}, function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 9
});
// invoke "sumDefault" with object missing some defined members
client.request('sumDefault', {b: 10}, function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 12
});
// invoke "isArray" with an Object
client.request('isArray', {a: 5, b: 2, c: 9}, function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // true
});
client.request('sum', [1, 2, 3], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 6
});
}
export function test_example_17() {
var methods = {
// this function will be wrapped in jayson.Method with options given to the server
sum: function(args:any, done:any) {
done(null, sum(args));
},
// this method gets the raw params as first arg to handler
sumCollect: new jayson.Method({
handler: function(args:any, done:any) {
var total = sum(args);
done(null, total);
},
}),
// specifies some default values (alternate definition too)
sumDefault: new jayson.Method(function(args:any, done:any) {
var total = sum(args);
done(null, total);
}, {
params: {a: 2, b: 5} // map of defaults
}),
// this method returns true when it gets an array (which it always does)
isArray: new jayson.Method({
handler: function(args:any, done:any) {
var result = isArray(args);
done(null, result);
},
params: Array // could also be "Object"
})
};
var server = new jayson.Server(methods, {
// Given as options to jayson.Method when adding the method "sum"
params: Array
});
server.http().listen(3000);
// sums all numbers in an array
function sum(list:any) {
return reduce(list, function(sum:any, val:any) {
return sum + val;
}, 0);
}
}
export function test_example_18() {
var client = jayson.Client.http({
port: 3000
});
client.request('myNameIs', {name: 'Mr. Creosote'}, function(err:any, error:any, result:any) {
if(err) throw err;
console.log(result); // 'Your name is: Mr. Creosote'
});
}
export function test_example_19() {
var cors = require('cors');
var connect = require('connect');
var jsonParser = require('body-parser').json;
var app = connect();
var server = new jayson.Server({
myNameIs: function(args:any, callback:any) {
callback(null, 'Your name is: ' + args.name);
}
});
app.use(cors({methods: ['POST']}));
app.use(jsonParser());
app.use(server.middleware());
app.listen(3000);
}
export function test_example_20() {
var client = jaysonPromise.Client.http({
port: 3000
});
var reqs = [
client.request('add', [1, 2, 3, 4, 5]),
client.request('rejection', [])
];
Promise.all(reqs).then(function(responses:any) {
console.log(responses[0].result);
console.log(responses[1].error);
});
}
export function test_example_21() {
var server = new jayson.Server({
add: function(args:any) {
return new Promise(function(resolve, reject) {
var sum = reduce(args, function(sum:any, value:any) { return sum + value; }, 0);
resolve(sum);
});
},
// example on how to reject
rejection: function(args:any) {
return new Promise(function(resolve, reject) {
// server.error just returns {code: 501, message: 'not implemented'}
reject(server.error(501, 'not implemented'));
});
}
});
server.http().listen(3000);
}
export function test_example_22() {
var server = new jayson.Server({
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
// let the backend listen to *:3001
server.http().listen(3001);
}
export function test_example_23() {
var client = jayson.Client.http({
port: 3000 // the port of the frontend server
});
client.request('add', [5, 9], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 14
});
}
export function test_example_24() {
// create a server where "add" will relay a localhost-only server
var server = new jayson.Server({
add: jayson.Client.http({
port: 3001
})
});
// let the frontend server listen to *:3000
server.http().listen(3000);
}
export function test_example_25() {
var fs = require('fs');
var path = require('path');
// Read node's tls documentation for more information about these options:
// https://nodejs.org/api/tls.html#tls_tls_connect_options_callback
var options = {
key: fs.readFileSync(path.resolve('./../../../test/fixtures/keys/agent1-key.pem')),
cert: fs.readFileSync(path.resolve('./../../../test/fixtures/keys/agent1-cert.pem')),
// This is necessary only if the client uses the self-signed certificate.
ca: [ fs.readFileSync(path.resolve('./../../../test/fixtures/keys/ca1-cert.pem')) ],
port: 3000,
host: 'localhost'
};
// create a client
var client = jayson.Client.tls(options);
// invoke "add"
client.request('add', [1, 1], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 2
});
}
export function test_example_26() {
var fs = require('fs');
var path = require('path');
// Read node's tls documentation for more information about these options:
// https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
var options = {
key: fs.readFileSync(path.resolve('./../../../test/fixtures/keys/agent1-key.pem')),
cert: fs.readFileSync(path.resolve('./../../../test/fixtures/keys/agent1-cert.pem')),
requestCert: true,
// This is necessary only if the client uses the self-signed certificate.
ca: [ fs.readFileSync(path.resolve('./../../../test/fixtures/keys/ca1-cert.pem')) ],
};
// create a server
var server = new jayson.Server({
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
// Bind a http interface to the server and let it listen to localhost:3000
server.tls(options).listen(3000);
class Counter {
count:number;
constructor(value?:number) {
this.count = value || 0;
}
increment() {
this.count += 1;
}
}
exports.replacer = function(key:any, value:any) {
if(value instanceof Counter) {
return {$class: 'counter', $props: {count: value.count}};
}
return value;
};
exports.reviver = function(key:any, value:any) {
if(value && value.$class === 'counter') {
var obj = new Counter(value.$props.count);
return obj;
}
return value;
};
}
export function test_example_27() {
var shared = require('./shared');
var client = jayson.Client.http({
port: 3000,
reviver: shared.reviver,
replacer: shared.replacer
});
// create the object
var params = {
counter: new shared.Counter(2)
};
// invoke "increment"
client.request('increment', params, function(err:any, response:any) {
if(err) throw err;
var result = response.result;
console.log(
result instanceof shared.Counter, // true
result.count, // 3
params.counter === result // false - result is a new object
);
});
}
export function test_example_28() {
var shared = require('./shared');
// Set the reviver/replacer options
var options = {
reviver: shared.reviver,
replacer: shared.replacer
};
// create a server
var server = new jayson.Server({
increment: function(args:any, callback:any) {
args.counter.increment();
callback(null, args.counter);
}
}, options);
server.http().listen(3000);
}
export function test_example_29() {
var client = jayson.Client.http({
port: 3000
});
// the third parameter is set to "null" to indicate a notification
client.request('ping', [], null, function(err:any) {
if(err) throw err;
console.log('ok'); // request was received successfully
});
}
export function test_example_30() {
var server = new jayson.Server({
ping: function(args:any, callback:any) {
// do something, do nothing
callback();
}
});
server.http().listen(3000);
}
export function test_example_31() {
// create a client
var client = jayson.Client.http({
port: 3000
});
// invoke "add_2"
client.request('add_2', [3], function(err:any, response:any) {
if(err) throw err;
console.log(response.result); // 5!
});
}
export function test_example_32() {
var methods = {
add: function(args:any, callback:any) {
callback(null, args[0] + args[1]);
}
};
var server = new jayson.Server(methods, {
router: <jayson.ServerRouterFunction>function(method:any, params:any) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
if(method === 'add_2') {
var fn = (server.getMethod('add') as jayson.Method).getHandler() as jayson.MethodHandler;
return new jayson.Method(function(args:any, done:any) {
args.unshift(2);
fn.call(server, args, done);
});
}
}
});
server.http().listen(3000);
}
export function test_Middleware() {
var app = require('express') as Express;
var server = new jayson.Server({
add: function (args:any, callback:any) {
callback(null, args[0] + args[1]);
}
});
var jsonParser = require('body-parser').json;
// parse request body before the jayson middleware
app.use(jsonParser());
app.use(server.middleware());
app.listen(3000);
}
export function test_ServerOptions() {
const server = new jayson.Server({}, {
useContext: true,
});
server.options.useContext = false;
server.errorMessages[jayson.Server.errors.PARSE_ERROR] = 'This is a parse error';
}
export function test_MethodPromise() {
const fn1:jaysonPromise.MethodHandlerType = async function(args:jaysonPromise.RequestParamsLike, context:object, callback:jaysonPromise.JSONRPCCallbackTypePlain):Promise<jaysonPromise.JSONRPCResultLike> {
return {};
};
const fn2:jaysonPromise.MethodHandlerType = function(args:jaysonPromise.RequestParamsLike, callback:jaysonPromise.JSONRPCCallbackTypePlain) {
callback(null, {});
};
new jaysonPromise.Method(fn1, {useContext: true});
new jaysonPromise.Method(fn2);
}
export function test_Method() {
const fn1:jayson.MethodHandlerType = function(args:jayson.RequestParamsLike, context:object, callback:jayson.JSONRPCCallbackTypePlain) {
callback(this.error(-32602));
};
const fn2:jayson.MethodHandlerType = function(args:jayson.RequestParamsLike, callback:jayson.JSONRPCCallbackTypePlain) {
callback(null, {});
};
const methodWithContext = new jayson.Method(fn1, {useContext: true});
const methodWithoutContext = new jayson.Method(fn2);
const server = new jayson.Server({}, {useContext: true});
// called with and without context
methodWithContext.execute(server, {}, {}, function () {});
methodWithContext.execute(server, {}, function () {});
}
export function test_Utils() {
jayson.Utils.response(null, {}, null, 2);
jayson.Utils.response({code: 1234, message: 'hello', data: {test: true}}, {}, null, 2);
jayson.Utils.response({code: 1234, message: 'hello', data: {test: true}}, {}, null, 1);
jayson.Utils.generateId();
jayson.Utils.merge({a: true}, {a: false, b: true});
jayson.Utils.Response.isValidResponse({}, 2);
jayson.Utils.Response.isValidResponse({});
jayson.Utils.Response.isValidError({}, 1);
jayson.Utils.Response.isValidError({});
jayson.Utils.Request.isValidRequest({}, 1);
jayson.Utils.Request.isNotification({});
jayson.Utils.Request.isBatch([]);
jayson.Utils.Request.isValidRequest({});
jayson.Utils.JSON.stringify({}, null, function(err?:Error, str?:string) {});
jayson.Utils.JSON.stringify({}, {}, function(err?:Error, str?:string) {});
jayson.Utils.JSON.parse('', null, function(err?:Error, data?:object) {});
jayson.Utils.JSON.parse('', {}, function(err?:Error, data?:object) {});
}
export function test_ServerEventEmitter() {
const server = new jayson.Server({}, {
useContext: true,
});
server.on('request', function(request:jayson.JSONRPCRequestLike) {
});
server.on('response', function(request:jayson.JSONRPCRequestLike, response:jayson.JSONRPCRequestLike) {
});
}
export function test_clientBrowser () {
const shared = require('./shared');
const callServer = function(request:string, callback:((err?:Error | null, response?:string) => void)) {
callback(null, '{}');
};
const client = new jaysonBrowserClient(callServer, {
reviver: shared.reviver,
replacer: shared.replacer,
generator: () => String(Math.round(Math.random() * 10000)),
version: 2,
});
client.request('multiply', [5, 5], function(err?: Error | null, error?: jayson.JSONRPCErrorLike, result?: jayson.JSONRPCResultLike) {
if(err) throw err;
console.log(result); // 25
});
client.request('multiply', [5, 5], '2', function(err?: Error | null, error?: jayson.JSONRPCErrorLike, result?: jayson.JSONRPCResultLike) {
if(err) throw err;
console.log(result); // 25
});
const r1 = client.request('multiply', {asdf: true});
const r2 = client.request('multiply', [3, 9]);
client.request([r1, r2], function (err: jayson.JSONRPCErrorLike, results?: Array<jayson.JSONRPCResultLike>) {
if(err) throw err;
console.log(results); // 25
});
}
export function test_clientBrowserPromise () {
const shared = require('./shared');
const callServer = function(request:string):Promise<string> {
return Promise.resolve(JSON.stringify({code: -1, message: 'we have an error'}));
};
const client = new jaysonPromiseBrowserClient(callServer, {
reviver: shared.reviver,
replacer: shared.replacer,
generator: () => String(Math.round(Math.random() * 10000)),
version: 2,
});
client.request('multiply', [5, 5]).then(function (response) {});
client.request('multiply', [5, 5], '2').then(function (response) {});
const r1 = client.request('multiply', {asdf: true}, undefined, false);
const r2 = client.request('multiply', [3, 9], undefined, false);
client.request([r1, r2]).then(function (response) {});
}