Validate API request query (#4642)

* fix: refactor to accommodate authentication, transaction and pagination together into ctx.state

* feat: allow passing response type to APIContext

* feat: preliminary work for initial review

* fix: use unknown for base types

* fix: api/attachments

* fix: api/documents

* fix: jsdoc comment for input

* fix: replace at() with index access for compatibility

* fix: validation err message

* fix: error handling

* fix: remove unnecessary extend
This commit is contained in:
Apoorv Mishra
2023-01-05 20:24:03 +05:30
committed by GitHub
parent 445d19f43e
commit b6141442b7
12 changed files with 297 additions and 192 deletions

View File

@@ -13,7 +13,7 @@ import { authorize } from "@server/policies";
import { presentAttachment } from "@server/presenters";
import { APIContext } from "@server/types";
import { getPresignedPost, publicS3Endpoint } from "@server/utils/s3";
import { assertIn, assertUuid } from "@server/validation";
import { assertIn } from "@server/validation";
import * as T from "./schema";
const router = new Router();
@@ -24,7 +24,7 @@ router.post(
validate(T.AttachmentsCreateSchema),
transaction(),
async (ctx: APIContext<T.AttachmentCreateReq>) => {
const { name, documentId, contentType, size, preset } = ctx.input;
const { name, documentId, contentType, size, preset } = ctx.input.body;
const { auth, transaction } = ctx.state;
const { user } = auth;
@@ -113,7 +113,7 @@ router.post(
auth(),
validate(T.AttachmentDeleteSchema),
async (ctx: APIContext<T.AttachmentDeleteReq>) => {
const { id } = ctx.input;
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const attachment = await Attachment.findByPk(id, {
rejectOnEmpty: true,
@@ -141,9 +141,10 @@ router.post(
}
);
const handleAttachmentsRedirect = async (ctx: APIContext) => {
const id = ctx.request.body?.id ?? ctx.request.query?.id;
assertUuid(id, "id is required");
const handleAttachmentsRedirect = async (
ctx: APIContext<T.AttachmentsRedirectReq>
) => {
const id = (ctx.input.body.id ?? ctx.input.query.id) as string;
const { user } = ctx.state.auth;
const attachment = await Attachment.findByPk(id, {
@@ -165,7 +166,17 @@ const handleAttachmentsRedirect = async (ctx: APIContext) => {
}
};
router.get("attachments.redirect", auth(), handleAttachmentsRedirect);
router.post("attachments.redirect", auth(), handleAttachmentsRedirect);
router.get(
"attachments.redirect",
auth(),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect
);
router.post(
"attachments.redirect",
auth(),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect
);
export default router;