Skip to content

Commit

Permalink
refactor(rest): use on-finished module instead of hand-written solution
Browse files Browse the repository at this point in the history
  • Loading branch information
bajtos committed Feb 12, 2019
1 parent 914ad47 commit 49aeac9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
2 changes: 2 additions & 0 deletions packages/rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@types/express": "^4.11.1",
"@types/express-serve-static-core": "^4.16.0",
"@types/http-errors": "^1.6.1",
"@types/on-finished": "^2.3.1",
"@types/serve-static": "1.13.2",
"@types/type-is": "^1.6.2",
"ajv": "^6.5.1",
Expand All @@ -40,6 +41,7 @@
"http-errors": "^1.6.3",
"js-yaml": "^3.11.0",
"lodash": "^4.17.11",
"on-finished": "^2.3.0",
"openapi-schema-to-json-schema": "^2.1.0",
"openapi3-ts": "^1.0.0",
"path-to-regexp": "^3.0.0",
Expand Down
15 changes: 9 additions & 6 deletions packages/rest/src/router/static-assets-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@

import {Context} from '@loopback/context';
import {OperationObject, SchemasObject} from '@loopback/openapi-v3-types';
import {Router, RequestHandler, static as serveStatic} from 'express';
import {RequestHandler, Router, static as serveStatic} from 'express';
import {PathParams} from 'express-serve-static-core';
import * as HttpErrors from 'http-errors';
import * as onFinished from 'on-finished';
import {ServeStaticOptions} from 'serve-static';
import {promisify} from 'util';
import {RequestContext} from '../request-context';
import {
OperationArgs,
Expand Down Expand Up @@ -70,6 +72,8 @@ export class StaticAssetsRoute implements RouteEntry, ResolvedRoute {
}
}

const onFinishedAsync = promisify(onFinished);

/**
* Execute an Express-style callback-based request handler.
*
Expand All @@ -86,11 +90,9 @@ function executeRequestHandler(
request: Request,
response: Response,
): Promise<boolean> {
return new Promise((resolve, reject) => {
const onceFinished = () => resolve(true);
response.once('finish', onceFinished);
handler(request, response, (err: Error) => {
response.removeListener('finish', onceFinished);
const responseWritten = onFinishedAsync(response).then(() => true);
const handlerFinished = new Promise<boolean>((resolve, reject) => {
handler(request, response, err => {
if (err) {
reject(err);
} else {
Expand All @@ -99,4 +101,5 @@ function executeRequestHandler(
}
});
});
return Promise.race([handlerFinished, responseWritten]);
}

0 comments on commit 49aeac9

Please sign in to comment.