-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add luxify function for converting traditional middleware (#183)
- Loading branch information
1 parent
39ce152
commit 81f52fc
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} | ||
}); | ||
} |