@flatfile/plugin-record-hook
Overview
This plugin exports a function named recordHook
that sets up an event listener for the commit:created
event.
The purpose of this plugin is to provide a concise syntax for running custom logic on individual data records in Flatfile.
INSTALL
npm i @flatfile/plugin-record-hook @flatfile/hooks
Import
import { recordHook } from '@flatfile/plugin-record-hook'
import type { FlatfileRecord } from '@flatfile/hooks'
Usage
Pass recordHook
to a Flatfile data listener and provide a function to run when data is added or updated.
1. Create a listener
Set up a listener to configure Flatfile and respond to data events:
export default function(listener) {
//simple listener
listener.on("**", (event) => {
console.log(
`-> My event listener received an event: ${JSON.stringify(event.topic)}`)
});
}
2. Listen for data changes
Use the this plugin to set up a hook that responds to data changes:
import { recordHook } from '@flatfile/plugin-record-hook'
import { FlatfileRecord } from '@flatfile/hooks'
listener.use(
recordHook('my-sheet', (record: FlatfileRecord, event: FlatfileEvent) => {
// Your logic goes here
})
)
Replace my-sheet
with the slug of the Sheet you want to attach this hook to.
Example usage
This example sets up a record hook using listener.use to modify records in the “my-sheet” sheet.
When a record is processed by the hook, it checks if the “firstName” and “lastName” fields exist and if the “fullName” field is not already populated. If these conditions are met, it sets the “fullName” field by concatenating the “firstName” and “lastName” values with a space in between.
Additionally, it adds a comment to the “fullName” field in the user interface indicating that it was populated from the first and last name.
listener.use(
recordHook('my-sheet', (record: FlatfileRecord, event: FlatfileEvent) => {
const firstName = record.get('firstName')
const lastName = record.get('lastName')
if (firstName && lastName && !record.get('fullName')) {
record.set('fullName', `${firstName} ${lastName}`)
record.addComment(
'fullName',
'Full name was populated from first and last name.'
)
}
return record
})
)