Hooks
Hooks are actions that are triggered when specific CRUD operations occur through the Pruvious collection API. You can add hooks by creating a TypeScript file in the hooks
directory located in the root of your project.
Example
Here's an example of a hook that sends an email to newly created users:
# hooks/users/after-create.ts
import { defineHook } from '#pruvious'
export default defineHook('users', 'afterCreate', async ({ record }) => {
// Send email to: record.email
})
Definition
The defineHook
function accepts the following arguments:
Argument | Description |
---|---|
| The name of a defined collection. |
| Specifies when the hook is triggered. The following list contains valid values, with those exclusive to multi-entry collections indicated by the M symbol:
|
| The hook function accepts a single |
Altering queries
A common use case for utilizing hooks is modifying the currentQuery
before executing it. For instance, you can display records belonging to a specific user in the dashboard. Here's an example:
# hooks/articles/before-read.ts
import { defineHook } from '#pruvious'
export default defineHook('articles', 'beforeRead', ({ currentQuery, user }) => {
currentQuery.where('author', user?.id ?? null)
})
Please note that users can still update and delete articles from other users. To prevent this, you can use the beforeUpdate
and beforeDelete
hooks to add the same where
clause as in the beforeRead
hook. Additionally, you can implement a beforeCreate
hook to assign the current user ID to the author field. Here's how:
# hooks/articles/before-create.ts
import { defineHook } from '#pruvious'
defineHook('articles', 'beforeCreate', ({ input, user }) => {
input.author = user?.id ?? null
})
Standard hooks
Pruvious has only one default predefined hook:
Hook | Description |
---|---|
| The hook clears the redirect cache after creating or updating a redirect. |
To disable this hook, set the standardHooks.redirects
option to false
in your nuxt.config.ts
file.
Last updated on November 13, 2024 at 12:37