summaryrefslogtreecommitdiffstats
path: root/examples/proxy/index.js
blob: 5f35049203e85f22cec0a55e83b5514274269e33 (plain)
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
const { Pool, Client } = require('../../')
const http = require('http')
const proxy = require('./proxy')

const pool = new Pool('http://localhost:4001', {
  connections: 256,
  pipelining: 1
})

async function run () {
  await Promise.all([
    new Promise(resolve => {
      // Proxy
      http.createServer((req, res) => {
        proxy({ req, res, proxyName: 'example' }, pool).catch(err => {
          if (res.headersSent) {
            res.destroy(err)
          } else {
            for (const name of res.getHeaderNames()) {
              res.removeHeader(name)
            }
            res.statusCode = err.statusCode || 500
            res.end()
          }
        })
      }).listen(4000, resolve)
    }),
    new Promise(resolve => {
      // Upstream
      http.createServer((req, res) => {
        res.end('hello world')
      }).listen(4001, resolve)
    })
  ])

  const client = new Client('http://localhost:4000')
  const { body } = await client.request({
    method: 'GET',
    path: '/'
  })

  for await (const chunk of body) {
    console.log(String(chunk))
  }
}

run()

// TODO: Add websocket example.