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

3.5 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  Property,
  AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
import {
  DedupeStrategy,
  Polling,
  pollingHelper,
} from '@activepieces/pieces-common';
import crypto from 'crypto';
import dayjs from 'dayjs';
import { oracleDbAuth } from '../common/auth';
import { OracleDbClient } from '../common/client';
import { oracleDbProps } from '../common/props';

type OrderDirection = 'ASC' | 'DESC';

const polling: Polling<
  AppConnectionValueForAuthProperty<typeof oracleDbAuth>,
  {
    tableName: string;
    orderBy: string;
    orderDirection: OrderDirection | undefined;
  }
> = {
  strategy: DedupeStrategy.LAST_ITEM,
  items: async ({ auth, propsValue, lastItemId }) => {
    const client = new OracleDbClient(auth.props);

    const lastItem = lastItemId as string;
    const lastOrderKey = lastItem ? lastItem.split('|')[0] : null;
    const direction = propsValue.orderDirection || 'DESC';

    let sql: string;
    const binds: Record<string, unknown> = {};

    if (lastOrderKey === null) {
      sql = `SELECT * FROM "${propsValue.tableName}" ORDER BY "${propsValue.orderBy}" ${direction} FETCH FIRST 5 ROWS ONLY`;
    } else {
      const operator = direction === 'DESC' ? '>=' : '<=';
      sql = `SELECT * FROM "${propsValue.tableName}" WHERE "${propsValue.orderBy}" ${operator} :lastKey ORDER BY "${propsValue.orderBy}" ${direction}`;
      binds['lastKey'] = lastOrderKey;
    }

    const { rows } = await client.execute(sql, binds);

    return (rows as Record<string, unknown>[]).map((row) => {
      const rowHash = crypto
        .createHash('md5')
        .update(JSON.stringify(row))
        .digest('hex');
      const isTimestamp = dayjs(row[propsValue.orderBy] as string).isValid();
      const orderValue = isTimestamp
        ? dayjs(row[propsValue.orderBy] as string).toISOString()
        : row[propsValue.orderBy];
      return {
        id: orderValue + '|' + rowHash,
        data: row,
      };
    });
  },
};

export const newRowTrigger = createTrigger({
  auth: oracleDbAuth,
  name: 'new_row',
  classification: 'READ',
  displayName: 'New Row',
  description: 'Triggers when a new row is created',
  aiMetadata: {
    description: 'Fires when a new row appears in the configured Oracle Database table. Polls the table ordered by the chosen order column (defaulting to newest first) and emits each newly seen row; represents a freshly inserted record detected by the ordering key.',
  },
  props: {
    description: Property.MarkDown({
      value: `**NOTE:** Fetches latest rows using the order column (newest first), then keeps polling for new rows.`,
    }),
    tableName: oracleDbProps.tableName(),
    orderBy: oracleDbProps.orderBy(),
    orderDirection: Property.StaticDropdown<OrderDirection>({
      displayName: 'Order Direction',
      description: 'Sort direction to fetch newest rows first',
      required: true,
      options: {
        options: [
          { label: 'Ascending', value: 'ASC' },
          { label: 'Descending', value: 'DESC' },
        ],
      },
      defaultValue: 'DESC',
    }),
  },
  type: TriggerStrategy.POLLING,
  sampleData: {},

  async onEnable(context) {
    await pollingHelper.onEnable(polling, context);
  },

  async onDisable(context) {
    await pollingHelper.onDisable(polling, context);
  },

  async run(context) {
    return await pollingHelper.poll(polling, context);
  },

  async test(context) {
    return await pollingHelper.test(polling, context);
  },
});