|
| 1 | +// Gateway implementation |
| 2 | + |
| 3 | +'use strict' |
| 4 | + |
| 5 | +const gateway = require('../index') |
| 6 | +const ConsistentHash = require('consistent-hash') |
| 7 | + |
| 8 | +const targets = [ |
| 9 | + 'http://localhost:3000', |
| 10 | + 'http://localhost:3001', |
| 11 | + 'http://localhost:3002', |
| 12 | +] |
| 13 | + |
| 14 | +const consistentHash = new ConsistentHash() |
| 15 | +targets.forEach((target) => consistentHash.add(target)) |
| 16 | + |
| 17 | +gateway({ |
| 18 | + routes: [ |
| 19 | + { |
| 20 | + proxyHandler: (req, res, url, proxy, proxyOpts) => { |
| 21 | + const target = consistentHash.get(req.path) |
| 22 | + proxyOpts.base = target |
| 23 | + |
| 24 | + return proxy(req, res, url, proxyOpts) |
| 25 | + }, |
| 26 | + prefix: '/api', |
| 27 | + }, |
| 28 | + ], |
| 29 | +}) |
| 30 | + .start(8080) |
| 31 | + .then(() => console.log('API Gateway listening on 8080 port!')) |
| 32 | + |
| 33 | +// Below is the services implementation, commonly located on separated projects |
| 34 | +const express = require('express') |
| 35 | + |
| 36 | +// service1.js |
| 37 | +const service1 = express() |
| 38 | +service1.get('/orders/:orderId', (req, res) => { |
| 39 | + res.header('Service-Id', 'service1') |
| 40 | + res.send('Order from service 1!') |
| 41 | +}) |
| 42 | +service1.listen(3000, () => { |
| 43 | + console.log('Service 1 running!') |
| 44 | +}) |
| 45 | + |
| 46 | +// service2.js |
| 47 | +const service2 = express() |
| 48 | + |
| 49 | +service2.get('/orders/:orderId', (req, res) => { |
| 50 | + res.header('Service-Id', 'service2') |
| 51 | + res.send('Order from service 2!') |
| 52 | +}) |
| 53 | + |
| 54 | +service2.listen(3001, () => { |
| 55 | + console.log('Service 2 running!') |
| 56 | +}) |
| 57 | + |
| 58 | +// service3.js |
| 59 | +const service3 = express() |
| 60 | + |
| 61 | +service3.get('/orders/:orderId', (req, res) => { |
| 62 | + res.header('Service-Id', 'service3') |
| 63 | + res.send('Order from service 3!') |
| 64 | +}) |
| 65 | + |
| 66 | +service3.listen(3002, () => { |
| 67 | + console.log('Service 3 running!') |
| 68 | +}) |
0 commit comments