lib/src/http/kernel/module/AbstractResolvedRouteHandlerHTTPModule.ts
garrettmills f496046461
All checks were successful
continuous-integration/drone/push Build is passing
File-based response support & static server
- Clean up UniversalPath implementation
    - Use Readable/Writable types correctly for stream methods
    - Add .list() methods for getting child files

- Make Response body specify explicit types and support
  writing Readable streams to the body

- Create a static file server that supports directory listing
2021-07-07 20:13:23 -05:00

36 lines
1.4 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'
import {UniversalPath} from '../../../util'
import {file} from '../../response/FileResponseFactory'
/**
* 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 ( object instanceof UniversalPath ) {
await file(object).write(request)
} else if ( typeof object !== 'undefined' ) {
await json(object).write(request)
} else {
await plaintext('').write(request)
}
}
}