📌
【Convex】NextJs14 と Convex【#15 Convex Create】
【#15 Convex Create】
YouTube: https://youtu.be/DWTCSjeAOKw
今回はカードの作成の関数を実装します。
カードに設定する画像はこちらから「svg」の画像をお借りしています。
convex/schema.ts
import { v } from "convex/values";
import { defineSchema, defineTable } from "convex/server";
export default defineSchema({
cards: defineTable({
title: v.string(),
orgId: v.string(),
authorId: v.string(),
authorName: v.string(),
cardType: v.string(),
imageUrl: v.string(),
}).index("by_org", ["orgId"]),
});
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;
},
});
Discussion