Hooks
SonicJs has a flexible hook system that always you to inject your own custom code into various core function without have to alter the core code or recreate their primary functions
Hooks are associated with the main CRUD functions of the API. They are defined in the schema file for each table.
Let's take a look at the hooks for the users
table:
export const hooks: ApiConfig["hooks"] = {
resolveInput: {
create: async (context, data) => {
if (data && data.password) {
data.password = await hashString(data.password);
}
return data;
},
},
};
On the above example, we have a hook that is called before a new user is created. It hashes the password before it is saved to the database.
Hooks are primarily used to create or modify data before it is saved to the database with the following two properties available:
- create
- update
Ultimately this approach allows you keep any custom validations and business logic related to your data model in one place.
If however, your data processing needs are more complex, you can always create a custom route.