Skip to content

Commit d298d67

Browse files
committed
Create HttpRequest class for node.js Body
1 parent 2146e47 commit d298d67

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

src/index.ts

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,40 @@
11
import pump = require('pump')
2-
import { Request, Response, Headers, createHeaders } from 'servie'
2+
import { Request, Response, Headers, createHeaders, RequestOptions } from 'servie'
33
import { createBody, Body } from 'servie/dist/body/node'
44
import { IncomingMessage, ServerResponse } from 'http'
55
import { TLSSocket } from 'tls'
66
import { finalhandler } from 'servie-finalhandler'
77
import { errorhandler } from 'servie-errorhandler'
88

9-
export type App = (req: Request, next: () => Promise<Response>) => Promise<Response>
9+
/**
10+
* Node.js HTTP request options.
11+
*/
12+
export interface HttpRequestOptions extends RequestOptions {
13+
body?: Body
14+
}
15+
16+
/**
17+
* Node.js HTTP request class.
18+
*/
19+
export class HttpRequest extends Request {
20+
21+
body: Body
22+
23+
constructor (options: HttpRequestOptions) {
24+
super(options)
25+
this.body = options.body || createBody()
26+
}
27+
28+
}
29+
30+
/**
31+
* HTTP server application signature.
32+
*/
33+
export type App = (req: HttpRequest, next: () => Promise<Response>) => Promise<Response>
1034

35+
/**
36+
* HTTP server options.
37+
*/
1138
export interface Options {
1239
production?: boolean
1340
logError?: (err: any) => void
@@ -20,7 +47,7 @@ export function createHandler (app: App, options: Options = {}) {
2047
return function (request: IncomingMessage, response: ServerResponse): Promise<void> {
2148
let hasResponded = false
2249

23-
const req = new Request({
50+
const req = new HttpRequest({
2451
connection: {
2552
localAddress: request.socket.localAddress,
2653
localPort: request.socket.localPort,
@@ -29,7 +56,7 @@ export function createHandler (app: App, options: Options = {}) {
2956
encrypted: !!(request.socket as TLSSocket).encrypted
3057
},
3158
method: request.method,
32-
url: request.url!,
59+
url: request.url || '/',
3360
body: createBody(request),
3461
headers: createHeaders(request.rawHeaders)
3562
})
@@ -60,7 +87,7 @@ export function createHandler (app: App, options: Options = {}) {
6087
}
6188

6289
if (!(res.body instanceof Body)) {
63-
throw new TypeError('Transport only supports node.js bodies')
90+
throw new TypeError('HTTP transport only supports node.js bodies')
6491
}
6592

6693
Promise.all([

0 commit comments

Comments
 (0)