Trigger when a Notion Database Item has changed

This script triggers when a record in a Notion database has changed. Note: This trigger should not run more often than every 2 minutes, since Notion rounds the last edit time to a full minute. Calling it more often may result in changes not being recognized.

Script· trigger notion

by peter kappelt640 · 5/26/2023

  • Submitted by peter kappelt640 Deno
    Created 1080 days ago
    1
    import { Resource, getState, setState } from "https://deno.land/x/[email protected]/mod.ts";
    2
    import { Client } from "npm:@notionhq/client";
    3
    
    
    4
    /**
    5
     * See https://developers.notion.com/reference/post-database-query
    6
     */
    7
    export async function main(
    8
      auth: Resource<"notion">,
    9
      database_id: string = d291b756c0914f2984c208924a116cca,
    10
      filter_properties?: string[],
    11
    ) {
    12
      const state = await getState();
    13
      let lastCheck = new Date(state);
    14
      if(!state) {
    15
        //this is the first run, state is not yet set
    16
        lastCheck = new Date();  
    17
        await setState(lastCheck);
    18
      }
    19
    
    
    20
      const client = new Client({ auth: auth.token });
    21
      if (!filter_properties?.filter(Boolean).length) {
    22
        filter_properties = undefined;
    23
      }
    24
      const entries = await client.databases.query({
    25
        database_id,
    26
        filter_properties,
    27
        filter: {
    28
          "timestamp": "last_edited_time",
    29
          "last_edited_time": {
    30
            "after": lastCheck.toISOString()
    31
          }
    32
        }
    33
      });
    34
    
    
    35
      const editDates = entries.results.map(r => new Date(r.last_edited_time));
    36
      const lastEntryEdit = new Date(Math.max(...editDates));
    37
      if(editDates.length){
    38
        await setState(lastEntryEdit);
    39
      }
    40
    
    
    41
      return entries.results;
    42
    }
    43