UNPKG

1.56 kBJavaScriptView Raw
1'use strict'
2
3const { Duplex } = require('stream')
4const headersFactory = require('./headers')
5
6module.exports = class Response extends Duplex {
7 _read () {
8 this.push(this.toString())
9 this.push(null)
10 }
11
12 _write (chunk, encoding, onwrite) {
13 this._headersSent = true
14 this._buffer.push(chunk.toString())
15 if (this._asynchronous) {
16 setTimeout(onwrite, 0)
17 } else {
18 onwrite()
19 }
20 }
21
22 setHeader (name, value) {
23 this._headers[name] = value
24 }
25
26 writeHead (statusCode, headers = {}) {
27 this._statusCode = statusCode
28 Object.keys(headers).forEach(header => {
29 this._headers[header] = headers[header]
30 })
31 }
32
33 flushHeaders () {
34 this._headersSent = true
35 }
36
37 end () {
38 this._headersSent = true
39 return super.end.apply(this, arguments)
40 }
41
42 constructor (options) {
43 super(options)
44 this._buffer = []
45 this._headers = headersFactory()
46 this._headersSent = false
47 let resolver
48 this._waitForFinish = new Promise(resolve => {
49 resolver = resolve
50 })
51 this.on('finish', () => resolver(this))
52 }
53
54 get headers () {
55 return this._headers
56 }
57
58 get statusCode () {
59 return this._statusCode
60 }
61
62 get headersSent () {
63 return this._headersSent
64 }
65
66 toString () {
67 return this._buffer.join('')
68 }
69
70 waitForFinish () {
71 return this._waitForFinish
72 }
73
74 isInitial () {
75 return this._buffer.length === 0 &&
76 !this._headersSent &&
77 Object.keys(this._headers).length === 0
78 }
79
80 setAsynchronous () {
81 this._asynchronous = true
82 }
83}