UNPKG

2.49 kBJavaScriptView Raw
1const Aborted = require('./Aborted');
2
3/**
4 * Extends protocol for mounting to express endpoint
5 */
6exports.mountExpress = () => Protocol => {
7 return class extends Protocol {
8 mount(consumer) {
9 return (request, response, next) => {
10 consumer({ ...request.body, context: 'http', httpContext: { request, response } })
11 .then(identity => {
12 request.identity = identity;
13 next();
14 })
15 .catch(error => {
16 // If authentication aborted. We'll just skip this route.
17 if (error instanceof Aborted) {
18 return null;
19 }
20
21 next(error);
22 })
23 ;
24 };
25 }
26 }
27};
28
29/**
30 * Extends protocol for mounting to koa endpoint
31 */
32exports.mountKoa = () => Protocol => {
33 return class extends Protocol {
34 mount(consumer) {
35 return (ctx, next) => consumer({
36 ...ctx.request.body,
37 context: 'http',
38 httpContext: ctx
39 }).then(identity => {
40 ctx.identity = identity;
41 return next();
42 }).catch(error => {
43 // If authentication aborted. We'll just skip this route.
44 if (!error instanceof Aborted) {
45 throw error;
46 }
47 });
48 }
49 }
50};
51
52
53/**
54 * Extends protocol for mounting to a Socket.IO channel
55 */
56exports.mountSocketIO = () => Protocol => {
57 return class extends Protocol {
58 mount(consumer) {
59 return (socket, next) => consumer({
60 context: 'socket',
61 ...socket.handshake.query,
62 socketContext: socket
63 }).then(identity => {
64 socket.identity = identity;
65 next();
66 }).catch((error) => next(error));
67 }
68 }
69};
70
71/**
72 * Extends protocol for mounting to an Yargs command
73 */
74exports.mountYargs = () => Protocol => {
75 return class extends Protocol {
76 mount(consumer) {
77 return async argv => {
78 const identity = await consumer({
79 context: 'console',
80 ...argv
81 });
82
83 return {
84 ...argv,
85 identity
86 };
87 }
88 }
89 }
90};