File size: 2,604 Bytes
1067b6f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | "use server";
import { db } from "@/db/db";
import { stores } from "@/db/schema";
import { currentUser, clerkClient } from "@clerk/nextjs/server";
import { eq, or } from "drizzle-orm";
import { z } from "zod";
import { createSlug } from "@/lib/createSlug";
export async function createStore(storeName: string) {
try {
const existingStore = await db
.select()
.from(stores)
.where(
or(eq(stores.name, storeName), eq(stores.slug, createSlug(storeName)))
);
if (existingStore.length > 0) {
const res = {
error: true,
message: "Sorry, a store with that name already exists.",
action: "Please try again.",
};
return res;
}
const [{ insertId: storeId }] = await db.insert(stores).values({
name: storeName,
slug: createSlug(storeName),
});
const user = await currentUser();
if (!user) {
const res = {
error: false,
message: "Unauthenticated",
action: "User is not authenticated",
};
return res;
}
if (user?.privateMetadata.storeId) {
const res = {
error: false,
message: "Store already exists",
action: "You already have a store",
};
return res;
}
await clerkClient.users.updateUser(user.id, {
privateMetadata: { ...user.privateMetadata, storeId },
});
const res = {
error: false,
message: "Store created",
action: "Success, your store has been created",
};
return res;
} catch (err) {
console.log(err);
const res = {
error: true,
message: "Sorry, an error occured creating your store. ",
action: "Please try again.",
};
return res;
}
}
export async function updateStore(args: {
name: string | null;
description: string | null;
industry: string | null;
}) {
const inputSchema = z.object({
name: z.string(),
description: z.string(),
industry: z.string(),
});
try {
const user = await currentUser();
if (!inputSchema.parse(args)) {
throw new Error("invalid input");
}
await db
.update(stores)
.set(args)
.where(eq(stores.id, Number(user?.privateMetadata.storeId)));
const res = {
error: false,
message: "Store details updated",
action: "Success, your store's details have been updated",
};
return res;
} catch (err) {
console.log(err);
const res = {
error: true,
message: "Sorry, an error occured updating your details.",
action: "Please try again.",
};
return res;
}
}
|