Edit and actions updates
This commit is contained in:
parent
0997e449bb
commit
f87bcc43a5
30 changed files with 759 additions and 139 deletions
93
apps/bridge-frontend/app/_lib/actions.ts
Normal file
93
apps/bridge-frontend/app/_lib/actions.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { db, Database } from "./database";
|
||||
|
||||
type AddActionArgs = {
|
||||
entity: string;
|
||||
table: keyof Database;
|
||||
fields: string[];
|
||||
currentState: any;
|
||||
formData: FormData;
|
||||
};
|
||||
|
||||
export const addAction = async ({
|
||||
entity,
|
||||
table,
|
||||
fields,
|
||||
currentState,
|
||||
formData,
|
||||
}: AddActionArgs) => {
|
||||
const newRecord = fields.reduce(
|
||||
(acc: Record<string, string>, field: string) => {
|
||||
// @ts-expect-error
|
||||
acc[field] = formData.get(field)?.toString() ?? null;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
await db.insertInto(table).values(newRecord).execute();
|
||||
|
||||
revalidatePath(`/${entity}`);
|
||||
|
||||
return {
|
||||
...currentState,
|
||||
values: newRecord,
|
||||
success: true,
|
||||
};
|
||||
};
|
||||
|
||||
type UpdateActionArgs = {
|
||||
entity: string;
|
||||
table: keyof Database;
|
||||
fields: string[];
|
||||
currentState: any;
|
||||
formData: FormData;
|
||||
};
|
||||
|
||||
export const updateAction = async ({
|
||||
entity,
|
||||
table,
|
||||
fields,
|
||||
currentState,
|
||||
formData,
|
||||
}: UpdateActionArgs) => {
|
||||
const id = currentState.values.id;
|
||||
const updatedRecord = fields.reduce(
|
||||
(acc: Record<string, string>, field: string) => {
|
||||
// @ts-expect-error
|
||||
acc[field] = formData.get(field)?.toString() ?? null;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
await db
|
||||
.updateTable(table)
|
||||
.set(updatedRecord)
|
||||
.where("id", "=", id)
|
||||
.executeTakeFirst();
|
||||
|
||||
revalidatePath(`/${entity}/${id}`);
|
||||
|
||||
return {
|
||||
...currentState,
|
||||
values: updatedRecord,
|
||||
success: true,
|
||||
};
|
||||
};
|
||||
|
||||
type DeleteActionArgs = {
|
||||
entity: string;
|
||||
table: keyof Database;
|
||||
id: string;
|
||||
};
|
||||
|
||||
export const deleteAction = async ({ entity, table, id }: DeleteActionArgs) => {
|
||||
await db.deleteFrom(table).where("id", "=", id).execute();
|
||||
|
||||
revalidatePath(`/${entity}`);
|
||||
|
||||
return true;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue