Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

2.7 KB
Raw Blame
import {
  createAction,
  DynamicPropsValue,
  MarkdownVariant,
  Property,
} from '@activepieces/pieces-framework';
import { Client } from '@notionhq/client';
import { NotionFieldMapping } from '../common/models';

import { notionAuth } from '../auth';
import { getNotionToken, notionCommon } from '../common';
import { updateDatabaseItemActionOutputSchema } from '../output-schemas';
export const updateDatabaseItem = createAction({
  auth: notionAuth,
  name: 'update_database_item',
  classification: 'WRITE',
  displayName: 'Update Database Item',
  description: 'Change field values on an existing database item.',
  audience: 'human',
  aiMetadata: {
    description:
      'Overwrites property fields on an existing Notion database item identified by its page id. Use when an agent must change values on a known record (status, assignee, dates) rather than create one; requires the database_id and the target item id. Idempotent: re-applying the same field values leaves the item in the same final state.',
    idempotent: true,
  },
  propertyGroups: [
    {
      key: 'item',
      display: 'section',
      label: 'Database item',
      icon: 'inbox',
      props: ['database_id', 'database_item_id'],
    },
    {
      key: 'changes',
      display: 'section',
      label: 'Changes',
      icon: 'sliders',
      props: ['changes_info', 'databaseFields'],
    },
  ],
  props: {
    database_id: notionCommon.database_id,
    database_item_id: notionCommon.database_item_id,
    changes_info: Property.MarkDown({
      value:
        'Empty fields keep their current value. Checkboxes are always saved as shown.',
      variant: MarkdownVariant.INFO,
    }),
    databaseFields: notionCommon.databaseFields,
  },
  outputSchema: updateDatabaseItemActionOutputSchema,
  async run(context) {
    const { database_id, database_item_id, databaseFields } =
      context.propsValue;

    if (!database_item_id) throw new Error('Item ID is required');

    const notionFields: DynamicPropsValue = {};

    const notion = new Client({
      auth: getNotionToken(context.auth),
      notionVersion: '2022-02-22',
    });
    const { properties } = await notion.databases.retrieve({
      database_id: database_id as unknown as string,
    });

    Object.keys(databaseFields).forEach((key) => {
      const value = databaseFields[key];
      if (
        value !== '' &&
        value !== undefined &&
        value !== null &&
        !(Array.isArray(value) && value.length === 0)
      ) {
        const fieldType: string = properties[key].type;
        notionFields[key] =
          NotionFieldMapping[fieldType].buildNotionType(value);
      }
    });
    return await notion.pages.update({
      page_id: database_item_id,
      properties: notionFields,
    });
  },
});