import * as TE from 'fp-ts/lib/TaskEither' ; import * as E from 'fp-ts/lib/Either' ; import * as t from 'io-ts' ; import { pipe } from 'fp-ts/lib/pipeable' ; import { NextApiRequest , NextApiResponse } from 'next' ; import { HttpError } from '../types' ; export const createMutationEndpoint = < P extends { input : t . Mixed ; error : t . Mixed ; apiError : t . Mixed ; payload : t . Mixed ; output : t . Mixed ; } > ( mutation , callback ) => ( req , res ) => { const decode = ( ) : E . Either < HttpError , t . TypeOf < P [ 'payload' ] > > => pipe ( mutation . props . input . decode ( req . body ) , E . mapLeft ( ( ) => ( { type : 'httpError' , status : 'badRequest' } ) ) ) ; pipe ( TE . fromEither ( decode ( ) ) , TE . chain ( callback ) ) ( ) . then ( output => { const json = mutation . props . output . encode ( output ) ; res . status ( 200 ) . json ( json ) ; } ) ; } ;