-
Notifications
You must be signed in to change notification settings - Fork 22
change the way response is used
#55
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bitgopatmcl
merged 2 commits into
BitGo:beta
from
bitgopatmcl:response-in-express-wrapper
Apr 29, 2022
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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,103 @@ | ||
| /** | ||
| * express-wrapper | ||
| * A simple, type-safe web server | ||
| */ | ||
|
|
||
| import express from 'express'; | ||
| import * as t from 'io-ts'; | ||
| import * as PathReporter from 'io-ts/lib/PathReporter'; | ||
|
|
||
| import { | ||
| HttpRoute, | ||
| HttpToKeyStatus, | ||
| KeyToHttpStatus, | ||
| RequestType, | ||
| ResponseType, | ||
| } from '@api-ts/io-ts-http'; | ||
|
|
||
| type NumericOrKeyedResponseType<R extends HttpRoute> = | ||
| | ResponseType<R> | ||
| | { | ||
| [S in keyof R['response']]: S extends keyof HttpToKeyStatus | ||
| ? { | ||
| type: HttpToKeyStatus[S]; | ||
| payload: t.TypeOf<R['response'][S]>; | ||
| } | ||
| : never; | ||
| }[keyof R['response']]; | ||
|
|
||
| export type ServiceFunction<R extends HttpRoute> = ( | ||
| input: RequestType<R>, | ||
| ) => NumericOrKeyedResponseType<R> | Promise<NumericOrKeyedResponseType<R>>; | ||
|
|
||
| export type RouteHandler<R extends HttpRoute> = | ||
| | ServiceFunction<R> | ||
| | { middleware: express.RequestHandler[]; handler: ServiceFunction<R> }; | ||
|
|
||
| export const getServiceFunction = <R extends HttpRoute>( | ||
| routeHandler: RouteHandler<R>, | ||
| ): ServiceFunction<R> => | ||
| 'handler' in routeHandler ? routeHandler.handler : routeHandler; | ||
|
|
||
| export const getMiddleware = <R extends HttpRoute>( | ||
| routeHandler: RouteHandler<R>, | ||
| ): express.RequestHandler[] => | ||
| 'middleware' in routeHandler ? routeHandler.middleware : []; | ||
|
|
||
| /** | ||
| * Dynamically assign a function name to avoid anonymous functions in stack traces | ||
| * https://stackoverflow.com/a/69465672 | ||
| */ | ||
| const createNamedFunction = <F extends (...args: any) => void>( | ||
| name: string, | ||
| fn: F, | ||
| ): F => Object.defineProperty(fn, 'name', { value: name }); | ||
|
|
||
| export const decodeRequestAndEncodeResponse = <Route extends HttpRoute>( | ||
| apiName: string, | ||
| httpRoute: Route, | ||
| handler: ServiceFunction<Route>, | ||
| ): express.RequestHandler => { | ||
| return createNamedFunction( | ||
| 'decodeRequestAndEncodeResponse' + httpRoute.method + apiName, | ||
| async (req, res) => { | ||
| const maybeRequest = httpRoute.request.decode(req); | ||
| if (maybeRequest._tag === 'Left') { | ||
| console.log('Request failed to decode'); | ||
| const validationErrors = PathReporter.failure(maybeRequest.left); | ||
| const validationErrorMessage = validationErrors.join('\n'); | ||
| res.writeHead(400, { 'Content-Type': 'application/json' }); | ||
| res.write(JSON.stringify({ error: validationErrorMessage })); | ||
| res.end(); | ||
| return; | ||
| } | ||
|
|
||
| let rawResponse: NumericOrKeyedResponseType<Route> | undefined; | ||
| try { | ||
| rawResponse = await handler(maybeRequest.right); | ||
| } catch (err) { | ||
| console.warn('Error in route handler:', err); | ||
| res.status(500).end(); | ||
| return; | ||
| } | ||
|
|
||
| const { type, payload } = rawResponse; | ||
| const status = typeof type === 'number' ? type : (KeyToHttpStatus as any)[type]; | ||
| if (status === undefined) { | ||
| console.warn('Unknown status code returned'); | ||
| res.status(500).end(); | ||
| return; | ||
| } | ||
| const responseCodec = httpRoute.response[status]; | ||
| if (responseCodec === undefined || !responseCodec.is(payload)) { | ||
| console.warn( | ||
| "Unable to encode route's return value, did you return the expected type?", | ||
| ); | ||
| res.status(500).end(); | ||
| return; | ||
| } | ||
|
|
||
| res.status(status).json(responseCodec.encode(payload)).end(); | ||
| }, | ||
| ); | ||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
will people be using this function? Cuz this would log in their console right which is something they might not want
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This function is intended to be package-internal. It's exported from this file but not re-exported from index. Does express have some kind of logging system? I don't see one skimming the docs.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
While I ponder this, I will point out the 12-factor way is "log to stdout/stderr"
https://12factor.net/logs
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok yeah its probably fine then
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did come across this over the weekend, is it destiny? or inapplicable
https://www.lpalmieri.com/posts/error-handling-rust/
Here we are handling the error on the developer's behalf, and it would be transparent if not for this error. According to this advice, logging here is the proper action