umami/src/pages/api/users/[id]/websites.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-08-20 05:23:15 +00:00
import { useAuth, useCors, useValidate } from 'lib/middleware';
2023-08-10 20:26:33 +00:00
import { NextApiRequestQueryBody, SearchFilter, WebsiteSearchFilterType } from 'lib/types';
2023-09-22 07:59:00 +00:00
import { pageInfo } from 'lib/schema';
2022-12-07 02:36:41 +00:00
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-08-10 20:26:33 +00:00
import { getWebsitesByUserId } from 'queries';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
2022-12-07 02:36:41 +00:00
2023-08-10 20:26:33 +00:00
export interface UserWebsitesRequestQuery extends SearchFilter<WebsiteSearchFilterType> {
id: string;
2023-08-20 05:23:15 +00:00
includeTeams?: boolean;
onlyTeams?: boolean;
2023-08-10 20:26:33 +00:00
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
includeTeams: yup.boolean(),
onlyTeams: yup.boolean(),
2023-09-22 07:59:00 +00:00
...pageInfo,
2023-08-20 05:23:15 +00:00
}),
};
2022-12-07 02:36:41 +00:00
export default async (
2023-08-20 05:23:15 +00:00
req: NextApiRequestQueryBody<UserWebsitesRequestQuery>,
2022-12-07 02:36:41 +00:00
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
2023-08-11 05:50:41 +00:00
2023-08-20 05:23:15 +00:00
req.yup = schema;
await useValidate(req, res);
2023-02-08 00:29:25 +00:00
const { user } = req.auth;
2023-09-22 07:59:00 +00:00
const { id: userId, page, pageSize, query, includeTeams, onlyTeams } = req.query;
2022-12-07 02:36:41 +00:00
if (req.method === 'GET') {
2023-02-08 00:29:25 +00:00
if (!user.isAdmin && user.id !== userId) {
return unauthorized(res);
}
2023-08-10 20:26:33 +00:00
const websites = await getWebsitesByUserId(userId, {
2023-09-22 07:59:00 +00:00
query,
2023-08-10 20:26:33 +00:00
page,
2023-09-06 19:52:08 +00:00
pageSize: +pageSize || undefined,
2023-08-10 20:26:33 +00:00
includeTeams,
2023-08-14 05:21:49 +00:00
onlyTeams,
2023-08-10 20:26:33 +00:00
});
2022-12-07 02:36:41 +00:00
2023-02-08 00:29:25 +00:00
return ok(res, websites);
2022-12-07 02:36:41 +00:00
}
return methodNotAllowed(res);
};