import { NextApiRequest , NextApiResponse } from "next" ; const getError = ( error ) => { if ( error . code && 400 <= error . code && error . code < 600 ) { return { status : 500 , message : error . message } ; } const matched = error . message . match ( /^([0-9]{3}):(.*)/ ) ; if ( matched && matched [ 1 ] && matched [ 2 ] ) { return { status : Number ( matched [ 1 ] ) , message : matched [ 2 ] . trim ( ) } ; } return { status : 500 , message : error . message } ; } ; export const withToken = ( handler ) => { return async function withTokenHandler ( req , res ) { if ( ! req . query . token ) { throw new Error ( "400: No token" ) ; } return handler ( req , res ) ; } ; } ; export const withError = ( handler ) => { return async function errorHandler ( req , res ) { try { return await handler ( req , res ) ; } catch ( error ) { const e = getError ( error ) ; return res . status ( e . status ) . json ( { ok : false , message : e . message } ) ; } } ; } ;