Skip to main content

Updating and deleting resources

On frontend

When you click on + or Edit buttons then apiPut function is used for updating resources:

const result = await apiPut<ApiResponse, Student>("student/d4507481-8b33-46e7-9c2e-606daab170cc", student);

On the frontend, resource deletion is performed via the apiDelete function. It takes the resource Id and sends a DELETE request to the backend:

const result = await apiDelete("Student", "d4507481-8b33-46e7-9c2e-606daab170cc");

On backend

Generic function crudUpdate accepts CrudUpdateConfig parameter and updates a resource:

const config: CrudUpdateConfig<Student> = {
resourceName: "Student",
resource: student,
userId: "d4507481-8b33-46e7-9c2e-606daab170cc",
};

const result = await crudUpdate(config);

On the backend, deletion is handled through crudDelete. It handles resource deletion safely: checks permissions, validates the resource, runs pre- and post-delete handlers, and then removes the resource:

const result = await crudDelete({
resourceName: "Student",
resourceId: "d4507481-8b33-46e7-9c2e-606daab170cc",
});

Adding custom crud handlers

If you need to execute custom actions before or after creating, updating, deleting or getting a resource, or even override the default behavior of certain CRUD operations, you can use the CRUD handlers. Saas-kit offers this types of handlers:

To create crud handler for student you can create a file inside server directory with the name student.handlers.ts. CRUD handlers must end with .handlers.ts extension. Inside export the custom handlers functions.

For example, we could create an crudHandlerType.afterUpdate handler that sends notification to its teacher about teacher's student if student was edited:

export async function afterUpdate(afterUpdateHandlerConfig: AfterUpdateCrudHandlerConfig<Student>) {
const student = afterUpdateHandlerConfig.modifiedResource;
const teacherUserId = student.teacher.userId;

await sendNotification(
teacherUserId,
"Student was edited",
`Student ${student.name}'s information was updated`,
);
}