File size: 1,679 Bytes
23ac194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict'

const { createHook } = require('node:async_hooks')
const { test } = require('node:test')
const Fastify = require('..')
const sget = require('simple-get').concat

const remainingIds = new Set()

createHook({
  init (asyncId, type, triggerAsyncId, resource) {
    if (type === 'content-type-parser:run') {
      remainingIds.add(asyncId)
    }
  },
  destroy (asyncId) {
    remainingIds.delete(asyncId)
  }
})

const app = Fastify({ logger: false })

test('test async hooks', (t, done) => {
  app.get('/', function (request, reply) {
    reply.send({ id: 42 })
  })

  app.post('/', function (request, reply) {
    reply.send({ id: 42 })
  })

  app.listen({ port: 0 }, function (err, address) {
    t.assert.ifError(err)

    sget({
      method: 'POST',
      url: 'http://localhost:' + app.server.address().port,
      body: {
        hello: 'world'
      },
      json: true
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)

      sget({
        method: 'POST',
        url: 'http://localhost:' + app.server.address().port,
        body: {
          hello: 'world'
        },
        json: true
      }, (err, response, body) => {
        t.assert.ifError(err)
        t.assert.strictEqual(response.statusCode, 200)

        sget({
          method: 'GET',
          url: 'http://localhost:' + app.server.address().port,
          json: true
        }, (err, response, body) => {
          t.assert.ifError(err)
          t.assert.strictEqual(response.statusCode, 200)
          app.close()
          t.assert.strictEqual(remainingIds.size, 0)
          done()
        })
      })
    })
  })
})