2022-02-17 20:56:24 +00:00
|
|
|
// Next.js API route support: https://vercel.com/docs/concepts/functions/serverless-functions
|
|
|
|
import type { NextApiRequest, NextApiResponse } from 'next'
|
2022-05-08 20:33:58 +00:00
|
|
|
import { listAllContracts } from 'web/lib/firebase/contracts'
|
|
|
|
import { applyCorsHeaders, CORS_UNRESTRICTED } from 'web/lib/api/cors'
|
2022-07-07 22:36:02 +00:00
|
|
|
import { toLiteMarket, ValidationError } from './_types'
|
|
|
|
import { z } from 'zod'
|
|
|
|
import { validate } from './_validate'
|
|
|
|
|
|
|
|
const queryParams = z
|
|
|
|
.object({
|
|
|
|
limit: z
|
|
|
|
.number()
|
2022-08-22 19:42:23 +00:00
|
|
|
.default(500)
|
2022-07-07 22:36:02 +00:00
|
|
|
.or(z.string().regex(/\d+/).transform(Number))
|
|
|
|
.refine((n) => n >= 0 && n <= 1000, 'Limit must be between 0 and 1000'),
|
|
|
|
before: z.string().optional(),
|
|
|
|
})
|
|
|
|
.strict()
|
2022-02-17 20:56:24 +00:00
|
|
|
|
|
|
|
export default async function handler(
|
|
|
|
req: NextApiRequest,
|
2022-06-09 01:08:06 +00:00
|
|
|
res: NextApiResponse
|
2022-02-17 20:56:24 +00:00
|
|
|
) {
|
2022-04-30 20:30:49 +00:00
|
|
|
await applyCorsHeaders(req, res, CORS_UNRESTRICTED)
|
2022-07-07 22:36:02 +00:00
|
|
|
|
|
|
|
let params: z.infer<typeof queryParams>
|
|
|
|
try {
|
|
|
|
params = validate(queryParams, req.query)
|
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof ValidationError) {
|
|
|
|
return res.status(400).json(e)
|
2022-06-09 01:08:06 +00:00
|
|
|
}
|
2022-07-07 22:36:02 +00:00
|
|
|
console.error(`Unknown error during validation: ${e}`)
|
|
|
|
return res.status(500).json({ error: 'Unknown error during validation' })
|
2022-06-09 01:08:06 +00:00
|
|
|
}
|
|
|
|
|
2022-07-07 22:36:02 +00:00
|
|
|
const { limit, before } = params
|
|
|
|
|
2022-06-09 01:08:06 +00:00
|
|
|
try {
|
|
|
|
const contracts = await listAllContracts(limit, before)
|
|
|
|
// Serve from Vercel cache, then update. see https://vercel.com/docs/concepts/functions/edge-caching
|
|
|
|
res.setHeader('Cache-Control', 's-maxage=1, stale-while-revalidate')
|
|
|
|
res.status(200).json(contracts.map(toLiteMarket))
|
|
|
|
} catch (e) {
|
|
|
|
res.status(400).json({
|
|
|
|
error:
|
|
|
|
'Failed to fetch markets (did you pass an invalid ID as the before parameter?)',
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2022-02-17 20:56:24 +00:00
|
|
|
}
|