Advertisement
Guest User

Untitled

a guest
Nov 28th, 2022
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface WrapperOptions<
  2.     Res,
  3.     Input extends AnyZodObject | undefined = undefined,
  4. > {
  5.     input?: Input
  6.     resolve(_args: {
  7.         input: Input extends AnyZodObject ? Input['_output'] : undefined
  8.         req: NextApiRequest
  9.         res: NextApiResponse<Res>
  10.     }): Promise<void>
  11. }
  12.  
  13. export function wrapper<
  14.     Res = unknown,
  15.     Input extends AnyZodObject | undefined = undefined,
  16. >({ input, resolve }: WrapperOptions<Res, Input>): NextApiHandler<unknown> {
  17.     return async function (req, res) {
  18.         try {
  19.             // eslint-disable-next-line @typescript-eslint/no-explicit-any
  20.             let parsedInput: any = undefined
  21.  
  22.             if (input) {
  23.                 const data = JSON.parse(req.body)
  24.                 parsedInput = await input.parseAsync(data)
  25.             }
  26.  
  27.             return resolve({ input: parsedInput, req, res })
  28.         } catch (e) {
  29.             res.status(500).send(fallbackErrorMessage)
  30.             return
  31.         }
  32.     }
  33. }
  34.  
  35. wrapper<{ data: number }>({
  36.     input: z.object({ hello: z.string(), bye: z.string() }),
  37.     async resolve({ input, req, res }) {
  38.         res.status(300).send({ data: 500 })
  39.         throw new APIError(405, 'Method not allowed')
  40.     },
  41. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement