Skip to content

Commit

Permalink
feat: add luxify function for converting traditional middleware (#183)
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharygolba authored Jun 25, 2016
1 parent 39ce152 commit 81f52fc
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
35 changes: 35 additions & 0 deletions src/packages/luxify/index.js
Original file line number Diff line number Diff line change
@@ -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<void|mixed> {
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;
}
21 changes: 21 additions & 0 deletions src/packages/luxify/utils/create-response-proxy.js
Original file line number Diff line number Diff line change
@@ -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];
}
}
});
}

0 comments on commit 81f52fc

Please sign in to comment.