|
| 1 | +const gateway = require('../index') |
| 2 | +const PORT = process.env.PORT || 8080 |
| 3 | +const onEnd = require('on-http-end') |
| 4 | +const CircuitBreaker = require('opossum') |
| 5 | + |
| 6 | +const REQUEST_TIMEOUT = 1.5 * 1000 |
| 7 | + |
| 8 | +const options = { |
| 9 | + timeout: REQUEST_TIMEOUT - 200, // If our function takes longer than "timeout", trigger a failure |
| 10 | + errorThresholdPercentage: 50, // When 50% of requests fail, trip the circuit |
| 11 | + resetTimeout: 30 * 1000 // After 30 seconds, try again. |
| 12 | +} |
| 13 | +const breaker = new CircuitBreaker(([req, res, url, proxy, proxyOpts]) => { |
| 14 | + return new Promise((resolve, reject) => { |
| 15 | + proxy(req, res, url, proxyOpts) |
| 16 | + onEnd(res, () => { |
| 17 | + // you can optionally evaluate response codes here... |
| 18 | + resolve() |
| 19 | + }) |
| 20 | + }) |
| 21 | +}, options) |
| 22 | + |
| 23 | +breaker.fallback(([req, res], err) => { |
| 24 | + if (err.code === 'EOPENBREAKER') { |
| 25 | + res.send({ |
| 26 | + message: 'Upps, looks like "public" service is down. Please try again in 30 seconds!' |
| 27 | + }, 503) |
| 28 | + } |
| 29 | +}) |
| 30 | + |
| 31 | +gateway({ |
| 32 | + routes: [{ |
| 33 | + timeout: REQUEST_TIMEOUT, |
| 34 | + proxyHandler: (...params) => breaker.fire(params), |
| 35 | + prefix: '/public', |
| 36 | + target: 'http://localhost:3000', |
| 37 | + docs: { |
| 38 | + name: 'Public Service', |
| 39 | + endpoint: 'swagger.json', |
| 40 | + type: 'swagger' |
| 41 | + } |
| 42 | + }] |
| 43 | +}).start(PORT).then(() => { |
| 44 | + console.log(`API Gateway listening on ${PORT} port!`) |
| 45 | +}) |
| 46 | + |
| 47 | +const service = require('restana')({}) |
| 48 | +service.get('/longop', (req, res) => { |
| 49 | + setTimeout(() => { |
| 50 | + res.send('This operation will trigger the breaker failure counter...') |
| 51 | + }, 2000) |
| 52 | +}) |
| 53 | +service.get('/hi', (req, res) => { |
| 54 | + res.send('Hello World!') |
| 55 | +}) |
| 56 | + |
| 57 | +service.start(3000).then(() => { |
| 58 | + console.log('Public service listening on 3000 port!') |
| 59 | +}) |
0 commit comments