Skip to content

Commit

Permalink
Check user deck existance
Browse files Browse the repository at this point in the history
  • Loading branch information
kubk committed Nov 21, 2023
1 parent f761759 commit 8216e94
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
18 changes: 18 additions & 0 deletions functions/db/deck/is-user-deck-exists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { EnvType } from "../../env/env-schema.ts";
import { getDatabase } from "../get-database.ts";
import { DatabaseException } from "../database-exception.ts";

export const isUserDeckExists = async (
envSafe: EnvType,
body: { user_id: number; deck_id: number },
) => {
const db = getDatabase(envSafe);

const userDeck = await db.from("user_deck").select().match(body);

if (userDeck.error) {
throw new DatabaseException(userDeck.error);
}

return userDeck.data.length ? userDeck.data[0] : null;
};
13 changes: 6 additions & 7 deletions functions/remove-deck-from-mine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { envSchema } from "./env/env-schema.ts";
import { createBadRequestResponse } from "./lib/json-response/create-bad-request-response.ts";
import { createJsonResponse } from "./lib/json-response/create-json-response.ts";
import { removeDeckFromMineDb } from "./db/deck/remove-deck-from-mine-db.ts";
import { getDeckByIdAndAuthorId } from "./db/deck/get-deck-by-id-and-author-id.ts";
import { createForbiddenRequestResponse } from "./lib/json-response/create-forbidden-request-response.ts";
import { isUserDeckExists } from "./db/deck/is-user-deck-exists.ts";

const requestSchema = z.object({
deckId: z.number(),
Expand All @@ -26,12 +26,11 @@ export const onRequestPost = handleError(async ({ env, request }) => {

const envSafe = envSchema.parse(env);

const canEdit = await getDeckByIdAndAuthorId(
envSafe,
input.data.deckId,
user.id,
);
if (!canEdit) {
const userDeckExists = await isUserDeckExists(envSafe, {
user_id: user.id,
deck_id: input.data.deckId,
});
if (!userDeckExists) {
return createForbiddenRequestResponse();
}

Expand Down

0 comments on commit 8216e94

Please sign in to comment.