【Convex】NextJs14 と Convex【#16 Convex Delete & Update】

2024/04/23に公開

【#16 Convex Delete & Update】

YouTube: https://youtu.be/yBK4W5BuY_0

https://youtu.be/yBK4W5BuY_0

今回はカードのデリートとアップデートの関数を作成します。

convex/card.ts
import { v } from "convex/values";

import { query, mutation } from "./_generated/server";

const images = [
  "/images/card_bg_01.svg",
  "/images/card_bg_02.svg",
  "/images/card_bg_03.svg",
];

export const get = query({
  args: {
    id: v.id("cards"),
    orgId: v.string(),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();

    if (!identity) {
      throw new Error("Unauthorized");
    }

    const card = await ctx.db.get(args.id);

    if (!card || card.orgId !== args.orgId) {
      throw new Error("Card not found.");
    }

    return card;
  },
});

export const create = mutation({
  args: {
    orgId: v.string(),
    title: v.string(),
    cardType: v.string(),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();

    if (!identity) {
      throw new Error("Unauthorized");
    }

    const randImageUrl = images[Math.floor(Math.random() * images.length)];

    const card = await ctx.db.insert("cards", {
      title: args.title,
      orgId: args.orgId,
      authorId: identity.subject,
      authorName: identity.name!,
      cardType: args.cardType,
      imageUrl: randImageUrl,
    });

    return card;
  },
});

export const deleteCard = mutation({
  args: {
    id: v.id("cards"),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();

    if (!identity) {
      throw new Error("Unauthorized");
    }

    await ctx.db.delete(args.id);
  },
});

export const updateCard = mutation({
  args: {
    id: v.id("cards"),
    title: v.string(),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();

    if (!identity) {
      throw new Error("Unauthorized");
    }

    if (!args.title) {
      throw new Error("Title is required");
    }

    if (args.title.length > 50) {
      throw new Error("Title must be less than 50 characters");
    }

    const card = await ctx.db.patch(args.id, {
      title: args.title,
    });

    return card;
  },
});

Discussion