refactor: add server side validation schema for views (#4953)

* refactor: move files to subfolder

* refactor: schema for views.list

* refactor: schema for views.create
This commit is contained in:
Mohamed ELIDRISSI
2023-03-01 03:20:27 +01:00
committed by GitHub
parent 9a96230976
commit bef9673530
5 changed files with 47 additions and 18 deletions

View File

@@ -0,0 +1 @@
export { default } from "./views";

View File

@@ -0,0 +1,23 @@
import z from "zod";
import BaseSchema from "../BaseSchema";
export const ViewsListSchema = BaseSchema.extend({
body: z.object({
/** Id of the document to retrieve the views for */
documentId: z.string().uuid(),
/** Whether to include views by suspended users */
includeSuspended: z.boolean().default(false),
}),
});
export type ViewsListReq = z.infer<typeof ViewsListSchema>;
export const ViewsCreateSchema = BaseSchema.extend({
body: z.object({
/** Id of the document to create the view for */
documentId: z.string().uuid(),
}),
});
export type ViewsCreateReq = z.infer<typeof ViewsCreateSchema>;

View File

@@ -1,40 +1,45 @@
import Router from "koa-router";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import validate from "@server/middlewares/validate";
import { View, Document, Event } from "@server/models";
import { authorize } from "@server/policies";
import { presentView } from "@server/presenters";
import { APIContext } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { assertUuid } from "@server/validation";
import * as T from "./schema";
const router = new Router();
router.post("views.list", auth(), async (ctx: APIContext) => {
const { documentId, includeSuspended = false } = ctx.request.body;
assertUuid(documentId, "documentId is required");
router.post(
"views.list",
auth(),
validate(T.ViewsListSchema),
async (ctx: APIContext<T.ViewsListReq>) => {
const { documentId, includeSuspended } = ctx.input.body;
const { user } = ctx.state.auth;
const { user } = ctx.state.auth;
const document = await Document.findByPk(documentId, {
userId: user.id,
});
authorize(user, "read", document);
const views = await View.findByDocument(documentId, { includeSuspended });
const document = await Document.findByPk(documentId, {
userId: user.id,
});
authorize(user, "read", document);
const views = await View.findByDocument(documentId, { includeSuspended });
ctx.body = {
data: views.map(presentView),
};
});
ctx.body = {
data: views.map(presentView),
};
}
);
router.post(
"views.create",
auth(),
rateLimiter(RateLimiterStrategy.OneThousandPerHour),
async (ctx: APIContext) => {
const { documentId } = ctx.request.body;
assertUuid(documentId, "documentId is required");
validate(T.ViewsCreateSchema),
async (ctx: APIContext<T.ViewsCreateReq>) => {
const { documentId } = ctx.input.body;
const { user } = ctx.state.auth;
const document = await Document.findByPk(documentId, {
userId: user.id,
});