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,9 +1,10 @@
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 { getInsights } from 'queries';
import * as yup from 'yup';
export interface InsightsRequestBody {
websiteId: string;
@ -16,6 +17,37 @@ export interface InsightsRequestBody {
groups: { name: string; type: string }[];
}
const schema = {
POST: yup.object().shape({
websiteId: yup.string().uuid().required(),
dateRange: yup
.object()
.shape({
startDate: yup.date().required(),
endDate: yup.date().required(),
})
.required(),
fields: yup
.array()
.of(
yup.object().shape({
name: yup.string().required(),
type: yup.string().required(),
value: yup.string().required(),
}),
)
.min(1)
.required(),
filters: yup.array().of(yup.string()).min(1).required(),
groups: yup.array().of(
yup.object().shape({
name: yup.string().required(),
type: yup.string().required(),
}),
),
}),
};
function convertFilters(filters) {
return filters.reduce((obj, { name, ...value }) => {
obj[name] = value;
@ -31,6 +63,9 @@ export default async (
await useCors(req, res);
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
if (req.method === 'POST') {
const {
websiteId,