diff --git a/src/index.js b/src/index.js index c33f2aca..1cbaf534 100644 --- a/src/index.js +++ b/src/index.js @@ -3,3 +3,5 @@ export { default as Logger } from './packages/logger'; export { default as Controller } from './packages/controller'; export { default as Serializer } from './packages/serializer'; export { default as Application } from './packages/application'; + +export { default as luxify } from './packages/luxify'; diff --git a/src/packages/luxify/index.js b/src/packages/luxify/index.js new file mode 100644 index 00000000..ebe67d18 --- /dev/null +++ b/src/packages/luxify/index.js @@ -0,0 +1,35 @@ +// @flow +import createResponseProxy from './utils/create-response-proxy'; +import type { IncomingMessage, ServerResponse } from 'http'; + +/** + * Convert traditional node HTTP server middleware into a lux compatible + * function for use in Controller#beforeAction. + */ +export default function luxify( + middleware: ( + req: IncomingMessage, + res: ServerResponse, + next: (err?: Error) => void + ) => void +): (req: IncomingMessage, res: ServerResponse) => Promise { + const result = function (req, res) { + return new Promise((resolve, reject) => { + res = createResponseProxy(res, resolve); + + middleware.call(null, req, res, (err) => { + if (err && err instanceof Error) { + reject(err); + } else { + resolve(); + } + }); + }); + }; + + Object.defineProperty(result, 'name', { + value: middleware.name + }); + + return result; +} diff --git a/src/packages/luxify/utils/create-response-proxy.js b/src/packages/luxify/utils/create-response-proxy.js new file mode 100644 index 00000000..361349a7 --- /dev/null +++ b/src/packages/luxify/utils/create-response-proxy.js @@ -0,0 +1,21 @@ +// @flow +import type { ServerResponse } from 'http'; + +export default function createResponseProxy( + res: ServerResponse, + resolve: (result: mixed) => void +): ServerResponse { + return new Proxy(res, { + get(target: ServerResponse, key: string, receiver: Proxy): ?mixed | void { + switch (key) { + case 'end': + case 'send': + case 'json': + return resolve; + + default: + return target[key]; + } + } + }); +}