tasko/actions/create-card/index.ts

67 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-02-16 01:49:19 +00:00
'use server';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { auth } from '@clerk/nextjs';
import { revalidatePath } from 'next/cache';
import { ACTION, ENTITY_TYPE } from '@prisma/client';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { db } from '@/lib/db';
import { createAuditLog } from '@/lib/create-audit-log';
import { createSafeAction } from '@/lib/create-safe-action';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { InputType, ReturnType } from './types';
import { CreateCard } from './schema';
2024-02-15 02:30:10 +00:00
const handler = async (data: InputType): Promise<ReturnType> => {
const { userId, orgId } = auth();
2024-02-16 01:49:19 +00:00
if (!userId || !orgId) return { error: 'Unauthorized' };
2024-02-15 02:30:10 +00:00
const { title, boardId, listId } = data;
let card;
try {
const list = await db.list.findUnique({
where: {
id: listId,
board: {
orgId,
},
},
});
2024-02-16 01:49:19 +00:00
if (!list) return { error: 'List not found' };
2024-02-15 02:30:10 +00:00
const lastCard = await db.card.findFirst({
where: { listId },
2024-02-16 01:49:19 +00:00
orderBy: { order: 'desc' },
2024-02-15 02:30:10 +00:00
select: { order: true },
});
const newOrder = lastCard ? lastCard.order + 1 : 1;
card = await db.card.create({
data: {
title,
listId,
order: newOrder,
},
});
await createAuditLog({
entityId: card.id,
entityTitle: card.title,
entityType: ENTITY_TYPE.CARD,
action: ACTION.CREATE,
});
} catch (error) {
return {
2024-02-16 01:49:19 +00:00
error: 'Failed to create card',
2024-02-15 02:30:10 +00:00
};
}
revalidatePath(`/board/${boardId}`);
return { data: card };
};
export const createCard = createSafeAction(CreateCard, handler);