Repository URL to install this package:
|
Version:
7.0.4 ▾
|
// import ExpressRequestObj from 'express/lib/request'
// import express from 'express'
// const req = new ExpressRequestObj()
// const app = express()
// const req = Object.create(ExpressRequestObj, {
// app: {
// configurable: true,
// enumerable: true,
// writable: true,
// value: app,
// },
// })
import { Socket } from 'net'
import { Transform } from 'stream'
import { IncomingMessage, IncomingHttpHeaders } from 'http'
/**
* @see https://github.com/apollographql/apollo-server/blob/master/packages/apollo-server-core/src/__tests__/runQuery.test.ts
* @see https://github.com/diachedelic/mock-req/blob/master/index.js
*
* @see https://github.com/howardabrams/node-mocks-http
* @see https://github.com/expressjs/express/blob/master/lib/express.js#L46
*
* @see https://github.com/diachedelic/mock-req
*/
export interface MockRequestOptions {
url: string
method: 'PUT' | 'PATCH' | 'POST' | 'GET' | 'OPTIONS'
headers: {
[key: string]: string
}
[key: string]: any
}
export class MockIncomingMessage extends Transform implements IncomingMessage {
_writableState: any
_readableState: any
_failError: any
method: string
url: string
headers: IncomingHttpHeaders | { [key: string]: any } | any
rawHeaders: any
// from IncomingMessage
socket: Socket
connection: Socket
destroy: any
httpVersion: string
httpVersionMajor: number
httpVersionMinor: number
trailers: { [key: string]: string | undefined }
rawTrailers: any
setTimeout: (msecs: number, callback: () => void) => this
constructor(options: MockRequestOptions = {} as MockRequestOptions) {
super()
this._writableState.objectMode = true
this._readableState.objectMode = false
// Copy unreserved options
const reservedOptions = ['method', 'url', 'headers', 'rawHeaders']
Object.keys(options).forEach(key => {
if (reservedOptions.includes(key) === false) {
this[key] = options[key]
}
})
this.method = options.method || 'GET'
this.url = options.url || ''
// Set header names
this.headers = {}
this.rawHeaders = []
if (options.headers) {
Object.keys(options.headers).forEach(key => {
let val = options.headers[key]
if (val !== undefined) {
if (typeof val !== 'string') {
// I think this is trying to convert it to a string? @@fork
val += ''
}
this.headers[key.toLowerCase()] = val
this.rawHeaders.push(key)
this.rawHeaders.push(val)
}
})
}
// Auto-end when no body
if (
this.method === 'GET' ||
this.method === 'HEAD' ||
this.method === 'DELETE'
) {
this.end()
}
}
_transform(chunk: string | Buffer, encoding, next) {
if (this._failError) {
return this.emit('error', this._failError)
}
if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) {
chunk = JSON.stringify(chunk)
}
this.push(chunk)
next()
}
// Causes the request to emit an error when the body is read.
_fail(error: Error | string) {
this._failError = error
}
}