Skip to content

Commit

Permalink
Feature/inv 122 템플릿 CRUD 메서드 구현 (#38)
Browse files Browse the repository at this point in the history
* feat: implement list templates api

* feat: 템플릿 단건 조회 api 구현

* feat: 템플릿 update api 구현

* feat: 템플릿 삭제 api 구현

* feat: 템플릿 생성 api 구현
  • Loading branch information
delphox60 authored Aug 14, 2024
1 parent 3706be3 commit fe1e361
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions src/lib/db/schema/templates.query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use server";
import { eq } from "drizzle-orm";
import { nanoid } from "nanoid";

import { db } from "~/lib/db";
import { templates } from "~/lib/db/schema/templates";

type CreateTemplateParams = {
title: string;
description?: string;
customFields?: Record<string, any>; // JSON data
};

type UpdateTemplateParams = {
id: string;
title?: string;
description?: string;
customFields?: Record<string, any>; // JSON data
};

export async function getAllTemplates() {
const result = await db.select().from(templates);
return result;
}

export async function getById(id: string) {
const result = await db.select().from(templates).where(eq(templates.id, id));
return result[0];
}

async function updateTemplate(params: UpdateTemplateParams) {
const { id, ...updates } = params;

if (!id) {
throw new Error("ID is required to update a template");
}

const currentTimestamp = new Date();

try {
await db
.update(templates)
.set({
...updates,
updatedAt: currentTimestamp,
})
.where(eq(templates.id, id));
} catch (error) {
console.error("Error updating template:", error);
throw new Error("Could not update template");
}
}

async function deleteTemplate(id: string): Promise<void> {
if (!id) {
throw new Error("ID is required to delete a template");
}

try {
await db.delete(templates).where(eq(templates.id, id));
} catch (error) {
console.error("Error deleting template:", error);
throw new Error("Could not delete template");
}
}

async function createTemplate(params: CreateTemplateParams): Promise<void> {
const { title, description, customFields } = params;

const id = nanoid();

const currentTimestamp = new Date();

try {
await db.insert(templates).values({
id,
title,
description,
customFields,
createdAt: currentTimestamp,
updatedAt: currentTimestamp,
});
} catch (error) {
console.error("Error creating template:", error);
throw new Error("Could not create template");
}
}

0 comments on commit fe1e361

Please sign in to comment.