Last active
September 10, 2019 07:35
-
-
Save dgieselaar/71667eaa6ac184b551e24a14c340a09c to your computer and use it in GitHub Desktop.
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
import t from 'io-ts'; | |
import { Request } from 'hapi'; | |
import { PathReporter } from 'io-ts/lib/PathReporter'; | |
import { isLeft } from 'fp-ts/lib/Either'; | |
interface Params { | |
path?: t.HasProps; | |
query?: t.HasProps; | |
body?: t.Any; | |
} | |
interface Route { | |
path: string; | |
method: 'GET' | 'POST' | 'PUT' | 'DELETE'; | |
params: Params; | |
handler: (request: Request) => {}; | |
} | |
export const createRoute = (route: Route) => { | |
const { params, handler, ...rest } = route; | |
return { | |
...rest, | |
handler: (request: Request) => { | |
const requestData = { | |
body: request.payload, | |
path: request.params, | |
query: request.query | |
}; | |
(Object.keys(params) as Array<keyof Params>).forEach(key => { | |
const codec = params[key] as t.Any; | |
const result = codec.decode(requestData[key]); | |
if (isLeft(result)) { | |
throw new Error(PathReporter.report(result).join('\n')); | |
} | |
}); | |
return handler(request); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment