62 lines
1.2 KiB
TypeScript
62 lines
1.2 KiB
TypeScript
import { objectLoop } from '@dzeio/object-util'
|
|
|
|
/**
|
|
* Simple builde to create a new Response object
|
|
*/
|
|
export default class ResponseBuilder {
|
|
|
|
private _body: BodyInit | null | undefined
|
|
public body(body: string | object | null | undefined) {
|
|
if (typeof body === 'object') {
|
|
this._body = JSON.stringify(body)
|
|
this.addHeader('Content-Type', 'application/json')
|
|
} else {
|
|
this._body = body
|
|
}
|
|
return this
|
|
}
|
|
|
|
private _headers: Headers = new Headers()
|
|
public headers(headers: HeadersInit ) {
|
|
if (headers instanceof Headers) {
|
|
this._headers = headers
|
|
} else {
|
|
this._headers = new Headers(headers)
|
|
}
|
|
return this
|
|
}
|
|
|
|
public addHeader(key: string, value: string) {
|
|
this._headers.append(key, value)
|
|
return this
|
|
}
|
|
|
|
public addHeaders(headers: Record<string, string>) {
|
|
objectLoop(headers, (value, key) => {
|
|
this.addHeader(key, value)
|
|
})
|
|
return this
|
|
}
|
|
|
|
public removeHeader(key: string) {
|
|
this._headers.delete(key)
|
|
return this
|
|
}
|
|
|
|
private _status?: number
|
|
public status(status: number) {
|
|
this._status = status
|
|
return this
|
|
}
|
|
|
|
public build(): Response {
|
|
const init: ResponseInit = {
|
|
headers: this._headers
|
|
}
|
|
if (this._status) {
|
|
init.status = this._status
|
|
}
|
|
return new Response(this._body, init)
|
|
}
|
|
}
|