Add api validations.

This commit is contained in:
Brian Cao 2023-08-19 22:23:15 -07:00
parent 7d5a24044a
commit 7a7233ead4
41 changed files with 690 additions and 180 deletions

View file

@ -1,33 +1,43 @@
import { canViewWebsite } from 'lib/auth';
import { useCors, useAuth } from 'lib/middleware';
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
import { ok, methodNotAllowed, unauthorized } from 'next-basics';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getRetention } from 'queries';
import * as yup from 'yup';
export interface RetentionRequestBody {
websiteId: string;
dateRange: { window; startDate: string; endDate: string };
timezone: string;
dateRange: { startDate: string; endDate: string };
}
export interface RetentionResponse {
startAt: number;
endAt: number;
}
const schema = {
POST: yup.object().shape({
websiteId: yup.string().uuid().required(),
dateRange: yup
.object()
.shape({
startDate: yup.date().required(),
endDate: yup.date().required(),
})
.required(),
}),
};
export default async (
req: NextApiRequestQueryBody<any, RetentionRequestBody>,
res: NextApiResponse<RetentionResponse>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
if (req.method === 'POST') {
const {
websiteId,
dateRange: { startDate, endDate },
timezone,
} = req.body;
if (!(await canViewWebsite(req.auth, websiteId))) {
@ -37,7 +47,6 @@ export default async (
const data = await getRetention(websiteId, {
startDate: new Date(startDate),
endDate: new Date(endDate),
timezone,
});
return ok(res, data);