Skip to content

Instantly share code, notes, and snippets.

@dgieselaar
Last active September 10, 2019 07:35
Show Gist options
  • Save dgieselaar/71667eaa6ac184b551e24a14c340a09c to your computer and use it in GitHub Desktop.
Save dgieselaar/71667eaa6ac184b551e24a14c340a09c to your computer and use it in GitHub Desktop.
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