Created
January 16, 2020 19:33
-
-
Save beerose/ebf80128ef8f441dfdeb275ddfa30cd4 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 { NowResponse } from '@now/node'; | |
import { fold } from 'fp-ts/lib/Either'; | |
import * as t from 'io-ts'; | |
import { reporter } from 'io-ts-reporters'; | |
type GetRequestValidator< | |
QueryValidator extends t.Any, | |
ParamsValidator extends t.Any | |
> = t.TypeC<{ | |
query: QueryValidator; | |
params: ParamsValidator; | |
}>; | |
interface GetRequestI< | |
QueryValidator extends t.Any, | |
ParamsValidator extends t.Any = t.Any | |
> extends Request { | |
query: t.TypeOf<QueryValidator>; | |
params: t.TypeOf<ParamsValidator>; | |
} | |
export type GetRequest< | |
QueryValidator extends t.Any | GetRequestValidator<any, any>, | |
ParamsValidator extends t.Any = t.Any | |
> = QueryValidator extends GetRequestValidator<infer Q, infer P> | |
? GetRequestI<Q, P> | |
: QueryValidator extends t.Any | |
? GetRequestI<QueryValidator, ParamsValidator> | |
: never; | |
export interface PostRequest<BodyValidator extends t.Any> extends Request { | |
body: t.TypeOf<BodyValidator>; | |
} | |
type GetDecoded<Decoder> = Decoder extends t.Decoder<any, infer A> ? A : never; | |
export function handleBadRequest<Decoder extends t.Decoder<any, any>>( | |
decoder: Decoder, | |
payload: unknown, | |
response: NowResponse, | |
): Promise<GetDecoded<Decoder>> { | |
return new Promise(resolve => { | |
const result = decoder.decode(payload); | |
fold(_err => { | |
response.status(400).json({ | |
errors: { | |
error: 'Bad request', | |
message: reporter(result).join('\n'), | |
}, | |
}); | |
}, resolve)(result); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment