Standard libraries that lift up your code.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.3 KiB

import {ResponseFactory} from './ResponseFactory'
import {Request} from '../lifecycle/Request'
import {ErrorWithContext, UniversalPath} from '../../util'
import {Logging} from '../../service/Logging'
* Helper function that creates a FileResponseFactory for the given path.
* @param path
export function file(path: UniversalPath): FileResponseFactory {
return new FileResponseFactory(path)
* HTTP response factory that sends a file referenced by a given UniversalPath.
export class FileResponseFactory extends ResponseFactory {
/** The file to be sent. */
public readonly path: UniversalPath,
) {
public async write(request: Request): Promise<Request> {
if ( !(await this.path.isFile()) ) {
throw new ErrorWithContext(`Cannot write non-file resource as response: ${this.path}`, {
path: this.path,
request.make<Logging>(Logging).debug(`Setting Content-Type of ${this.path} to ${this.path.contentType}...`)
request.response.setHeader('Content-Type', this.path.contentType || 'application/octet-stream')
request.response.setHeader('Content-Length', String(await this.path.sizeInBytes()))
request.response.body = await this.path.readStream()
return request