|
1 | 1 | const sharedConfig = require('@ladjs/shared-config'); |
2 | 2 | const jwt = require('koa-jwt'); |
| 3 | +const sse = require('koa-sse-stream'); |
3 | 4 |
|
4 | 5 | const logger = require('../helpers/logger'); |
5 | 6 | const routes = require('../routes'); |
6 | 7 | const config = require('../config'); |
7 | 8 |
|
8 | | -module.exports = { |
9 | | - ...sharedConfig('API'), |
10 | | - routes: routes.api, |
11 | | - logger, |
12 | | - hookBeforeRoutes(app) { |
13 | | - app.use(jwt(config.jwt)); |
14 | | - } |
| 9 | +module.exports = (opts = {}) => { |
| 10 | + const sseMiddleware = sse({ ...config.sse, ...opts.sse }); |
| 11 | + const jwtMiddleware = jwt({ |
| 12 | + ...config.jwt, |
| 13 | + ...opts.jwt, |
| 14 | + getToken(ctx, _) { |
| 15 | + // pull token off of url if it is the sse endpoint |
| 16 | + if (ctx.url.indexOf('/v1/sse') === 0) { |
| 17 | + const splitUrl = ctx.url.split('/'); |
| 18 | + |
| 19 | + if (splitUrl.length === 4) { |
| 20 | + return splitUrl[3]; |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return null; |
| 25 | + } |
| 26 | + }); |
| 27 | + |
| 28 | + return { |
| 29 | + ...sharedConfig('API'), |
| 30 | + port: config.port, |
| 31 | + ...opts, |
| 32 | + routes: routes.api, |
| 33 | + logger, |
| 34 | + hookBeforeRoutes(app) { |
| 35 | + app.use((ctx, next) => { |
| 36 | + // return early if jwt is set to false |
| 37 | + if (!opts.jwt && typeof opts.jwt === 'boolean') { |
| 38 | + return next(); |
| 39 | + } |
| 40 | + |
| 41 | + return jwtMiddleware(ctx, next); |
| 42 | + }); |
| 43 | + |
| 44 | + app.use((ctx, next) => { |
| 45 | + // only do this on sse route |
| 46 | + if (ctx.url.indexOf('/v1/sse') === 0) { |
| 47 | + return sseMiddleware(ctx, next); |
| 48 | + } |
| 49 | + |
| 50 | + return next(); |
| 51 | + }); |
| 52 | + } |
| 53 | + }; |
15 | 54 | }; |
0 commit comments