mirror of
https://codeberg.org/MarkusThielker/finances.git
synced 2025-04-12 05:08:43 +00:00
N-FIN-5: add entity create/update server action
This commit is contained in:
parent
dd2b62ed13
commit
978ba4bf58
1 changed files with 56 additions and 0 deletions
56
src/lib/actions/entityCreateUpdate.ts
Normal file
56
src/lib/actions/entityCreateUpdate.ts
Normal file
|
@ -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}`,
|
||||||
|
};
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue