function handler(req, res) {
  let receivedData = ''

  req.on('data', (data) => {
    receivedData += data.toString('utf8')
  })

  req.on('end', () => {
    const payload = JSON.parse(receivedData)
    const prompt = getShortenedPrompt(payload)

    if (RESPONSES.has(prompt) === false) {
      res.statusCode = 500
      res.write(`Unknown prompt:\n${prompt}`)
      res.end()
      return
    }

    const { headers, code, body, streamData } = RESPONSES.get(prompt)
    for (const [key, value] of Object.entries(headers)) {
      res.setHeader(key, value)
    }
    res.statusCode = code

    if (payload.stream === true) {
      // OpenAI streamed responses are double newline delimited lines that
      // are prefixed with the string `data: `. The end of the stream is
      // terminated with a `done: [DONE]` string.
      let outStream
      if (streamData !== 'do random') {
        outStream = finiteStream(streamData, { ...body })
      } else {
        outStream = randomStream({ ...body })
        let streamChunkCount = 0
        outStream.on('data', () => {
          if (streamChunkCount >= 100) {
            outStream.destroy()
            res.destroy()
          }
          streamChunkCount += 1
        })
      }

      outStream.pipe(res)
    } else {
      res.write(JSON.stringify(body))
      res.end()
    }
  })
}
Build a mock server that listens on a 127.0.0.1 and a random port that
responds with pre-defined responses based on the "prompt" sent by the
OpenAI client library.

@example
const { server, port } = await openaiMockServer()
const client = new OpenAI({
  baseURL: `http://127.0.0.1:${port}`,
  apiKey: 'some key'
 }

const res = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'You are a scientist.' }]
})
console.dir(res)

server.close()

@returns {Promise<object>} Has `server`, `host`, and `port` properties.