Hooks

Hooks in SchemaJS allow developers to define custom logic that is automatically executed before or after specific table operations. They provide a powerful way to inject additional behavior, such as validation, logging, transformations, or external API calls, into the lifecycle of database interactions. By using hooks, you can extend the functionality of your tables and ensure that certain tasks are performed consistently and automatically whenever data is inserted, updated, or deleted.

Motivation

The primary motivation behind hooks in SchemaJS is to decouple backend logic from core database operations and automate repetitive or complex database scripts in a streamlined and maintainable manner. By using hooks, developers can define automated behaviors that execute at specific points during a table’s lifecycle—such as before inserting a new record or after updating a row—without cluttering application code or manually managing these tasks with external scripts.

Defining

Hooks in SchemaJS are defined using the .on() method, which allows you to attach custom logic to specific table operations. Hooks can be set up for different events, such as inserts, updates, or deletes, and are triggered automatically when those operations occur. These hooks can execute any custom logic you need, such as data validation, transformation, or triggering external services.

new Table("orders")
    .addColumn(new Column("id").string())
    .addColumn(new Column("productId").string())
    .addColumn(new Column("quantity").number())
    .on("insert", async (rows) => {
        for(let newOrder of rows) {
            // Automatically update report summary after a new order is inserted
            await updateSalesReport(newOrder.productId, newOrder.quantity);
        }
    });

Last updated