lib/src/http/kernel/module/AbstractResolvedRouteHandlerHTTPModule.ts
garrettmills 1d5056b753
All checks were successful
continuous-integration/drone/push Build is passing
Setup eslint and enforce rules
2021-06-02 22:36:25 -05:00

32 lines
1.2 KiB
TypeScript

import {HTTPKernelModule} from '../HTTPKernelModule'
import {ResponseObject} from '../../routing/Route'
import {Request} from '../../lifecycle/Request'
import {plaintext} from '../../response/StringResponseFactory'
import {ResponseFactory} from '../../response/ResponseFactory'
import {json} from '../../response/JSONResponseFactory'
/**
* Base class for HTTP kernel modules that apply some response from a route handler to the request.
*/
export abstract class AbstractResolvedRouteHandlerHTTPModule extends HTTPKernelModule {
/**
* Given a response object, write the response to the request in the appropriate format.
* @param object
* @param request
* @protected
*/
protected async applyResponseObject(object: ResponseObject, request: Request): Promise<void> {
if ( (typeof object === 'string') || (typeof object === 'number') ) {
object = plaintext(String(object))
}
if ( object instanceof ResponseFactory ) {
await object.write(request)
} else if ( typeof object !== 'undefined' ) {
await json(object).write(request)
} else {
await plaintext('').write(request)
}
}
}