From 978ba4bf58463cfcb993a36ab411c2d18ea49c86 Mon Sep 17 00:00:00 2001 From: Markus Thielker <mail.markus.thielker@gmail.com> Date: Sat, 9 Mar 2024 18:03:04 +0100 Subject: [PATCH] N-FIN-5: add entity create/update server action --- src/lib/actions/entityCreateUpdate.ts | 56 +++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/lib/actions/entityCreateUpdate.ts diff --git a/src/lib/actions/entityCreateUpdate.ts b/src/lib/actions/entityCreateUpdate.ts new file mode 100644 index 0000000..1f22e3f --- /dev/null +++ b/src/lib/actions/entityCreateUpdate.ts @@ -0,0 +1,56 @@ +import { z } from 'zod'; +import { ActionResponse } from '@/lib/types/ActionResponse'; +import { entityFormSchema } from '@/lib/form-schemas/entityFormSchema'; +import { prismaClient } from '@/prisma'; +import { getUser } from '@/auth'; +import { URL_SIGN_IN } from '@/lib/constants'; + +export default async function entityCreateUpdate({ + id, + name, + type, +}: z.infer<typeof entityFormSchema>): Promise<ActionResponse> { + 'use server'; + + const user = await getUser(); + if (!user) { + return { + type: 'error', + message: 'You must be logged in to create an entity.', + redirect: URL_SIGN_IN, + }; + } + + try { + if (id) { + await prismaClient.entity.update({ + where: { + id: id, + }, + data: { + name: name, + type: type, + }, + }, + ); + } else { + await prismaClient.entity.create({ + data: { + userId: user.id, + name: name, + type: type, + }, + }); + } + } catch (e) { + return { + type: 'error', + message: 'Invalid entity data', + }; + } + + return { + type: 'success', + message: `Created an entity with name: ${name} and type: ${type}`, + }; +}