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

fix(tables): turning off a flow now removes its Tables trigger even when a copy of the table was imported (#16465)

Bartosz Majewski60f3ad3d1f58
diff --git a/brain/knowledge/data-storage-observability/tables.md b/brain/knowledge/data-storage-observability/tables.md
index 2947b8309d9..7ae8fa31f42 100644
--- a/brain/knowledge/data-storage-observability/tables.md
+++ b/brain/knowledge/data-storage-observability/tables.md
@@ -34,6 +34,7 @@ A built-in relational database inside Activepieces: users store structured data
- JSON import into an **existing** table is client-orchestrated and destructive-first: `tableHooks.importTableIntoExisting` clears records, deletes every field, renames, then recreates, as separate HTTP calls with no transaction. A failure after the clear leaves the table empty, so the import dialog validates the uploaded file with `tablesUtils.getTemplateError` in its form resolver, before the user can click Import. The import functions trust their typed input and do not re-validate; any new caller that feeds them unknown JSON must run the same check first. It checks the table name, the columns, the row structure, the field types and the dropdown options; `TableTemplate.fields[].type` is a bare `z.string()`, so the type check can't come from that schema. `externalId` is optional because already-exported files and `POST /v1/fields` allow it missing. Still unguarded: `MAX_FIELDS_PER_TABLE`, rows whose `fieldId` matches no column (they import as empty records), and a network failure mid-sequence. The client trims rows to the record limit, so the limit only bites if another writer adds rows during the import.
- Field `externalId` is optional on `POST /v1/fields` (`CreateFieldRequest`) but required on `POST /v1/tables`, whose `fields` are `FieldState[]`. So a template without column `externalId`s imports into an existing table but gets a 400 when used to create a new one.
- Re-importing into an existing table fires record webhooks for every row: the clear sends `deleted` and the insert sends `created`, so a flow on the deleted trigger runs once per old row and a flow on the created trigger runs once per imported row.
+- A table `externalId` is not unique within a project: `POST /v1/tables` accepts any `externalId`, and Export Template → Import table keeps it. The piece resolves an `externalId` to the newest table, so a Tables trigger's `onDisable` must not re-resolve it to find its webhook. It deletes its stored `webhookId` on every table sharing the `externalId` instead (`tablesCommon.deleteWebhookFromTablesWithExternalId`), which is exact because `deleteWebhook` is scoped by `projectId + tableId + id` (ENG-820).
- CSV import only appends rows to an open table. It maps CSV columns onto the table's existing fields through the table store, so the import dialog offers CSV only when it has both a `tableId` and that store, which means only inside the table editor. Elsewhere the dialog accepts JSON only. Columns map by position: an empty value imports as a blank cell, but a row missing a middle column shifts every later value into the wrong field.
### Key files
diff --git a/bun.lock b/bun.lock
index 7b14b728f8d..9afdc49a008 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10841,7 +10841,7 @@
},
"packages/pieces/core/tables": {
"name": "@activepieces/piece-tables",
- "version": "0.6.1",
+ "version": "0.6.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
diff --git a/packages/pieces/core/tables/package.json b/packages/pieces/core/tables/package.json
index 9d137083955..1bf53e1c45d 100644
--- a/packages/pieces/core/tables/package.json
+++ b/packages/pieces/core/tables/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-tables",
- "version": "0.6.1",
+ "version": "0.6.2",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
diff --git a/packages/pieces/core/tables/src/lib/common/index.ts b/packages/pieces/core/tables/src/lib/common/index.ts
index 0260560d209..385f84710fc 100644
--- a/packages/pieces/core/tables/src/lib/common/index.ts
+++ b/packages/pieces/core/tables/src/lib/common/index.ts
@@ -37,7 +37,7 @@ export const tablesCommon = {
refreshers: [],
options: async (_propsValue, context) => {
try {
- const tables = await fetchAllTables(context);
+ const tables = await fetchAllTables({ context });
if (!Array.isArray(tables) || tables.length === 0) {
return {
options: [],
@@ -225,6 +225,21 @@ export const tablesCommon = {
return response.body;
},
+ async deleteWebhookFromTablesWithExternalId({
+ externalId,
+ webhookId,
+ context,
+ }: {
+ externalId: string;
+ webhookId: string;
+ context: TablesApiContext;
+ }) {
+ const tables = await fetchAllTables({ context, externalIds: [externalId] });
+ for (const table of tables) {
+ await this.deleteWebhook({ tableId: table.id, webhookId, server: context.server });
+ }
+ },
+
async getRecentRecords({
tableId,
limit = 5,
@@ -270,7 +285,7 @@ export const tablesCommon = {
}
},
- async convertTableExternalIdToId(tableId: string, context: { server: { apiUrl: string, token: string }, project: { id: string } }) {
+ async convertTableExternalIdToId(tableId: string, context: TablesApiContext) {
const list: ListTablesRequest = {
externalIds: [tableId],
projectId: context.project.id,
@@ -290,10 +305,11 @@ export const tablesCommon = {
}
}
-const fetchAllTables = async (context: { server: { apiUrl: string, token: string }, project: { id: string } }): Promise<Table[]> => {
+const fetchAllTables = async ({ context, externalIds }: { context: TablesApiContext, externalIds?: string[] }): Promise<Table[]> => {
+ const query = { limit: 100, projectId: context.project.id, externalIds };
const res = await httpClient.sendRequest({
method: HttpMethod.GET,
- url: `${context.server.apiUrl}v1/tables?limit=100&projectId=${context.project.id}`,
+ url: `${context.server.apiUrl}v1/tables?${qs.stringify(query)}`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: context.server.token,
@@ -308,7 +324,7 @@ const fetchAllTables = async (context: { server: { apiUrl: string, token: string
while (next) {
const nextPage = await httpClient.sendRequest({
method: HttpMethod.GET,
- url: `${context.server.apiUrl}v1/tables?cursor=${next}&limit=100&projectId=${context.project.id}`,
+ url: `${context.server.apiUrl}v1/tables?${qs.stringify({ ...query, cursor: next })}`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: context.server.token,
@@ -319,4 +335,6 @@ const fetchAllTables = async (context: { server: { apiUrl: string, token: string
next = nextPageBody.next
}
return tables;
-}
\ No newline at end of file
+}
+
+type TablesApiContext = { server: { apiUrl: string, token: string }, project: { id: string } };
diff --git a/packages/pieces/core/tables/src/lib/triggers/deleted-record.ts b/packages/pieces/core/tables/src/lib/triggers/deleted-record.ts
index 31d6a40bede..a11b2b354e6 100644
--- a/packages/pieces/core/tables/src/lib/triggers/deleted-record.ts
+++ b/packages/pieces/core/tables/src/lib/triggers/deleted-record.ts
@@ -36,27 +36,22 @@ export const deletedRecordTrigger = createTrigger({
},
});
- context.store.put('webhookId', webhookId);
+ await context.store.put('webhookId', webhookId);
},
async onDisable(context) {
const tableExternalId = context.propsValue.table_id;
if ((tableExternalId ?? '').toString().length === 0) {
return;
}
- const tableId = await tablesCommon.convertTableExternalIdToId(tableExternalId, context);
-
const webhookId = await context.store.get<string>('webhookId');
if (!webhookId) {
return;
}
- await tablesCommon.deleteWebhook({
- tableId,
- webhookId: webhookId,
- server: {
- apiUrl: context.server.apiUrl,
- token: context.server.token,
- },
+ await tablesCommon.deleteWebhookFromTablesWithExternalId({
+ externalId: tableExternalId,
+ webhookId,
+ context,
});
},
async run(context) {
diff --git a/packages/pieces/core/tables/src/lib/triggers/new-record.ts b/packages/pieces/core/tables/src/lib/triggers/new-record.ts
index 7664126e1ac..c2d781aabae 100644
--- a/packages/pieces/core/tables/src/lib/triggers/new-record.ts
+++ b/packages/pieces/core/tables/src/lib/triggers/new-record.ts
@@ -36,26 +36,22 @@ export const newRecordTrigger = createTrigger({
},
});
- context.store.put('webhookId', webhookId);
+ await context.store.put('webhookId', webhookId);
},
async onDisable(context){
const tableExternalId = context.propsValue.table_id;
if ((tableExternalId ?? '').toString().length === 0) {
return;
}
- const tableId = await tablesCommon.convertTableExternalIdToId(tableExternalId, context);
const webhookId = await context.store.get<string>('webhookId');
if (!webhookId) {
return;
}
- await tablesCommon.deleteWebhook({
- tableId,
- webhookId: webhookId,
- server: {
- apiUrl: context.server.apiUrl,
- token: context.server.token,
- },
+ await tablesCommon.deleteWebhookFromTablesWithExternalId({
+ externalId: tableExternalId,
+ webhookId,
+ context,
});
},
async run(context){
diff --git a/packages/pieces/core/tables/src/lib/triggers/updated-record.ts b/packages/pieces/core/tables/src/lib/triggers/updated-record.ts
index 9e92fa1d36f..c1c0e869fc9 100644
--- a/packages/pieces/core/tables/src/lib/triggers/updated-record.ts
+++ b/packages/pieces/core/tables/src/lib/triggers/updated-record.ts
@@ -36,27 +36,22 @@ export const updatedRecordTrigger = createTrigger({
},
});
- context.store.put('webhookId', webhookId);
+ await context.store.put('webhookId', webhookId);
},
async onDisable(context) {
const tableExternalId = context.propsValue.table_id;
if ((tableExternalId ?? '').toString().length === 0) {
return;
}
- const tableId = await tablesCommon.convertTableExternalIdToId(tableExternalId, context);
-
const webhookId = await context.store.get<string>('webhookId');
if (!webhookId) {
return;
}
- await tablesCommon.deleteWebhook({
- tableId,
- webhookId: webhookId,
- server: {
- apiUrl: context.server.apiUrl,
- token: context.server.token,
- },
+ await tablesCommon.deleteWebhookFromTablesWithExternalId({
+ externalId: tableExternalId,
+ webhookId,
+ context,
});
},
async run(context) {
diff --git a/packages/pieces/core/tables/test/trigger-shared-external-id.test.ts b/packages/pieces/core/tables/test/trigger-shared-external-id.test.ts
new file mode 100644
index 00000000000..f1165870e33
--- /dev/null
+++ b/packages/pieces/core/tables/test/trigger-shared-external-id.test.ts
@@ -0,0 +1,277 @@
+/// <reference types="vitest/globals" />
+
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+import { createMockActionContext, Store, TableWebhookEventType } from '@activepieces/pieces-framework';
+import { randomUUID } from 'crypto';
+import qs from 'qs';
+import { tablesCommon } from '../src/lib/common';
+import { deletedRecordTrigger } from '../src/lib/triggers/deleted-record';
+import { newRecordTrigger } from '../src/lib/triggers/new-record';
+import { updatedRecordTrigger } from '../src/lib/triggers/updated-record';
+
+const PAGE_SIZE = 2;
+const CURSOR_PREFIX = 'seek+/=';
+
+const { tablesApi } = vi.hoisted(() => {
+ const tablesApi: FakeTablesApi = { tables: [], webhooks: [], requests: [] };
+ return { tablesApi };
+});
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const original = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...original,
+ httpClient: {
+ sendRequest: async (request: HttpRequest) => ({ status: 200, headers: {}, body: answer(request) }),
+ },
+ };
+});
+
+beforeEach(() => {
+ tablesApi.tables = [];
+ tablesApi.webhooks = [];
+ tablesApi.requests = [];
+});
+
+describe.each([
+ ['New Record', newRecordTrigger, TableWebhookEventType.RECORD_CREATED],
+ ['Updated Record', updatedRecordTrigger, TableWebhookEventType.RECORD_UPDATED],
+ ['Deleted Record', deletedRecordTrigger, TableWebhookEventType.RECORD_DELETED],
+])('Tables %s trigger', (_name, trigger, event) => {
+ afterEach(() => {
+ const unfilteredTableLists = tablesApi.requests.filter((request) => isTableList(request) && !request.url.includes('externalIds'));
+ expect(unfilteredTableLists).toEqual([]);
+ });
+
+ test('enabling subscribes the resolved table to this trigger\'s event', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+
+ await trigger.onEnable(hookContext(memoryStore()));
+
+ expect(tablesApi.webhooks).toEqual([expect.objectContaining({ tableId: 'original-table', events: [event] })]);
+ });
+
+ test('enabling and disabling without a selected table make no requests', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store, ''));
+ await trigger.onDisable(hookContext(store, ''));
+
+ expect(tablesApi.requests).toEqual([]);
+ });
+
+ test('disabling without a stored subscription makes no requests', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+
+ await trigger.onDisable(hookContext(memoryStore()));
+
+ expect(tablesApi.requests).toEqual([]);
+ });
+
+ test('disabling after the original table was deleted leaves the copy untouched', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ const otherFlowWebhook = { id: 'other-flow-on-copy', tableId: 'imported-copy' };
+ tablesApi.tables = [{ id: 'imported-copy', externalId: 'leads' }];
+ tablesApi.webhooks = [otherFlowWebhook];
+ await trigger.onDisable(hookContext(store));
+
+ expect(tablesApi.webhooks).toEqual([otherFlowWebhook]);
+ });
+
+ test('disabling when no table has the externalId anymore succeeds without deleting', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ tablesApi.tables = [];
+ tablesApi.webhooks = [];
+ await trigger.onDisable(hookContext(store));
+
+ expect(tablesApi.requests.filter((request) => request.method === HttpMethod.DELETE)).toEqual([]);
+ });
+
+ test('disabling twice leaves nothing behind and does not fail', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ tablesApi.tables = [{ id: 'imported-copy', externalId: 'leads' }, ...tablesApi.tables];
+ await trigger.onDisable(hookContext(store));
+ await trigger.onDisable(hookContext(store));
+
+ expect(tablesApi.webhooks).toEqual([]);
+ });
+
+ test('disabling leaves tables with a different externalId untouched', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ const unrelatedWebhook = { id: 'other-flow-on-customers', tableId: 'customers-table' };
+ tablesApi.tables = [...tablesApi.tables, { id: 'customers-table', externalId: 'customers' }];
+ tablesApi.webhooks = [...tablesApi.webhooks, unrelatedWebhook];
+ await trigger.onDisable(hookContext(store));
+
+ expect(tablesApi.webhooks).toEqual([unrelatedWebhook]);
+ expect(deletedTableIds()).toEqual(['original-table']);
+ });
+
+ test('disabling removes the subscription that enabling created', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ const subscribed = tablesApi.webhooks.map((webhook) => webhook.tableId);
+ await trigger.onDisable(hookContext(store));
+
+ expect(subscribed).toEqual(['original-table']);
+ expect(tablesApi.webhooks).toEqual([]);
+ });
+
+ test('disabling removes the subscription that enabling created, even after a second table took the same externalId', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ tablesApi.tables = [{ id: 'imported-copy', externalId: 'leads' }, ...tablesApi.tables];
+ await trigger.onDisable(hookContext(store));
+ const afterDisable = tablesApi.webhooks;
+ await trigger.onEnable(hookContext(store));
+
+ expect(afterDisable).toEqual([]);
+ expect(tablesApi.webhooks).toHaveLength(1);
+ });
+
+ test('disabling leaves the subscriptions of other flows on tables that share the externalId', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ tablesApi.tables = [{ id: 'imported-copy', externalId: 'leads' }, ...tablesApi.tables];
+ const otherFlowWebhooks = [
+ { id: 'other-flow-on-original', tableId: 'original-table' },
+ { id: 'other-flow-on-copy', tableId: 'imported-copy' },
+ ];
+ tablesApi.webhooks = [...tablesApi.webhooks, ...otherFlowWebhooks];
+ await trigger.onDisable(hookContext(store));
+
+ expect(tablesApi.webhooks).toEqual(otherFlowWebhooks);
+ });
+
+ test('disabling finds the subscribed table on a later page of tables that share the externalId', async () => {
+ tablesApi.tables = [{ id: 'original-table', externalId: 'leads' }];
+ const store = memoryStore();
+
+ await trigger.onEnable(hookContext(store));
+ tablesApi.tables = [
+ { id: 'copy-3', externalId: 'leads' },
+ { id: 'copy-2', externalId: 'leads' },
+ { id: 'copy-1', externalId: 'leads' },
+ ...tablesApi.tables,
+ ];
+ const otherFlowWebhook = { id: 'other-flow-on-original', tableId: 'original-table' };
+ tablesApi.webhooks = [...tablesApi.webhooks, otherFlowWebhook];
+ await trigger.onDisable(hookContext(store));
+
+ expect(tablesApi.webhooks).toEqual([otherFlowWebhook]);
+ });
+});
+
+describe('Tables table dropdown', () => {
+ test('lists every table in the project across pages', async () => {
+ tablesApi.tables = [
+ { id: 'table-1', externalId: 'leads' },
+ { id: 'table-2', externalId: 'leads' },
+ { id: 'table-3', externalId: 'customers' },
+ ];
+
+ const dropdown = await tablesCommon.table_id.options({}, hookContext(memoryStore()));
+
+ expect(dropdown.options.map((option) => option.value)).toEqual(['leads', 'leads', 'customers']);
+ });
+});
+
+function answer(request: HttpRequest): unknown {
+ tablesApi.requests = [...tablesApi.requests, request];
+ const url = new URL(request.url);
+ const path = url.pathname.replace(/^\/api\//, '');
+ const webhookPath = path.match(/^v1\/tables\/([^/]+)\/webhooks(?:\/([^/]+))?$/);
+ if (isTableList(request)) {
+ const { externalIds, cursor } = qs.parse(url.search.slice(1));
+ const matching = Array.isArray(externalIds)
+ ? tablesApi.tables.filter((table) => externalIds.includes(table.externalId))
+ : tablesApi.tables;
+ const offset = cursor === undefined ? 0 : pageOffset(cursor);
+ const nextOffset = offset + PAGE_SIZE;
+ return {
+ data: matching.slice(offset, nextOffset),
+ next: nextOffset < matching.length ? `${CURSOR_PREFIX}${nextOffset}` : null,
+ previous: null,
+ };
+ }
+ if (request.method === HttpMethod.POST && webhookPath) {
+ const { events } = request.body as { events: TableWebhookEventType[] };
+ const webhook = { id: `webhook-${randomUUID()}`, tableId: webhookPath[1], events };
+ tablesApi.webhooks = [...tablesApi.webhooks, webhook];
+ return webhook;
+ }
+ if (request.method === HttpMethod.DELETE && webhookPath) {
+ tablesApi.webhooks = tablesApi.webhooks.filter((webhook) => !(webhook.tableId === webhookPath[1] && webhook.id === webhookPath[2]));
+ return {};
+ }
+ throw new Error(`unexpected request ${request.method} ${request.url}`);
+}
+
+function pageOffset(cursor: unknown): number {
+ if (typeof cursor !== 'string' || !cursor.startsWith(CURSOR_PREFIX)) {
+ throw new Error(`cursor arrived altered: ${String(cursor)}`);
+ }
+ return Number(cursor.slice(CURSOR_PREFIX.length));
+}
+
+function isTableList(request: HttpRequest): boolean {
+ return request.method === HttpMethod.GET && new URL(request.url).pathname.endsWith('/v1/tables');
+}
+
+function deletedTableIds(): string[] {
+ return tablesApi.requests
+ .filter((request) => request.method === HttpMethod.DELETE)
+ .map((request) => new URL(request.url).pathname.split('/')[4]);
+}
+
+function hookContext(store: Store, tableExternalId = 'leads') {
+ return {
+ ...createMockActionContext({ propsValue: { table_id: tableExternalId } }),
+ webhookUrl: 'http://localhost:4200/api/v1/webhooks/flow-1',
+ payload: { body: {}, headers: {}, queryParams: {} },
+ server: { apiUrl: 'http://localhost:4200/api/', publicUrl: 'http://localhost:4200/', token: 'engine-token' },
+ store,
+ };
+}
+
+function memoryStore(): Store {
+ const entries = new Map<string, string>();
+ return {
+ async put<T>(key: string, value: T): Promise<T> {
+ entries.set(key, JSON.stringify(value));
+ return value;
+ },
+ async get<T>(key: string): Promise<T | null> {
+ const saved = entries.get(key);
+ return saved === undefined ? null : JSON.parse(saved);
+ },
+ async delete(key: string): Promise<void> {
+ entries.delete(key);
+ },
+ };
+}
+
+type FakeTablesApi = {
+ tables: { id: string; externalId: string }[];
+ webhooks: { id: string; tableId: string; events?: TableWebhookEventType[] }[];
+ requests: HttpRequest[];
+};
diff --git a/packages/server/api/test/integration/ce/tables/table.test.ts b/packages/server/api/test/integration/ce/tables/table.test.ts
index 2317eb04190..c08654537db 100644
--- a/packages/server/api/test/integration/ce/tables/table.test.ts
+++ b/packages/server/api/test/integration/ce/tables/table.test.ts
@@ -1,12 +1,14 @@
-import { apId } from '@activepieces/core-utils'
-import { FieldType, Table } from '@activepieces/shared'
+import { apId, isNil } from '@activepieces/core-utils'
+import { FieldType, Table, TableWebhookEventType } from '@activepieces/shared'
import { FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
import { db } from '../../../helpers/db'
import { describeWithAuth } from '../../../helpers/describe-with-auth'
import {
createMockCell,
createMockField,
+ createMockFlow,
createMockFolder,
createMockProject,
createMockRecord,
@@ -557,10 +559,89 @@ describe('Table API', () => {
expect(recordsResponse?.json().data.length).toBe(0)
})
})
+
+ describeWithAuth('Tables sharing an externalId', () => app!, (setup) => {
+ it('should list every table that shares an externalId, newest first', async () => {
+ const ctx = await setup()
+ const externalId = apId()
+ const older = await createAndSaveTable(ctx, { externalId, created: '2026-01-01T00:00:00.000Z' })
+ const newer = await createAndSaveTable(ctx, { externalId, created: '2026-02-01T00:00:00.000Z' })
+ await createAndSaveTable(ctx)
+
+ const response = await ctx.get('/v1/tables', { projectId: ctx.project.id, externalIds: [externalId] })
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(response?.json().data.map((table: Table) => table.id)).toEqual([newer.id, older.id])
+ })
+ })
+
+ describeWithAuth('POST and DELETE /v1/tables/:id/webhooks', () => app!, (setup) => {
+ it('should delete a webhook from the table it was created on', async () => {
+ const ctx = await setup()
+ const table = await createAndSaveTable(ctx)
+ const webhookId = await createWebhook({ ctx, tableId: table.id })
+
+ const response = await ctx.delete(`/v1/tables/${table.id}/webhooks/${webhookId}`)
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(await db.findOneBy('table_webhook', { id: webhookId })).toBeNull()
+ })
+
+ it('should leave a webhook when deleting it through another table with the same externalId', async () => {
+ const ctx = await setup()
+ const externalId = apId()
+ const original = await createAndSaveTable(ctx, { externalId })
+ const copy = await createAndSaveTable(ctx, { externalId })
+ const webhookId = await createWebhook({ ctx, tableId: original.id })
+
+ const response = await ctx.delete(`/v1/tables/${copy.id}/webhooks/${webhookId}`)
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(await db.findOneBy('table_webhook', { id: webhookId })).not.toBeNull()
+ })
+
+ it('should not delete a webhook on a table from another project', async () => {
+ const ctx = await setup()
+ const otherCtx = await createTestContext(app!)
+ const otherTable = await createAndSaveTable(otherCtx)
+ const webhookId = await createWebhook({ ctx: otherCtx, tableId: otherTable.id })
+
+ const response = await ctx.delete(`/v1/tables/${otherTable.id}/webhooks/${webhookId}`)
+
+ expect(response?.statusCode).toBe(StatusCodes.FORBIDDEN)
+ expect(await db.findOneBy('table_webhook', { id: webhookId })).not.toBeNull()
+ })
+
+ it('should remove a flow\'s webhooks when the flow is deleted', async () => {
+ const ctx = await setup()
+ const table = await createAndSaveTable(ctx)
+ const flow = createMockFlow({ projectId: ctx.project.id })
+ await db.save('flow', flow)
+ const webhookId = await createWebhook({ ctx, tableId: table.id, flowId: flow.id })
+
+ await databaseConnection().getRepository('flow').delete({ id: flow.id })
+
+ expect(await db.findOneBy('table_webhook', { id: webhookId })).toBeNull()
+ })
+ })
})
-async function createAndSaveTable(ctx: TestContext) {
- const table = createMockTable({ projectId: ctx.project.id })
- await db.save('table', table)
- return table
+async function createAndSaveTable(ctx: TestContext, table?: Partial<Table>) {
+ const mockTable = { ...createMockTable({ projectId: ctx.project.id }), ...table }
+ await db.save('table', mockTable)
+ return mockTable
+}
+
+async function createWebhook({ ctx, tableId, flowId }: { ctx: TestContext, tableId: string, flowId?: string }): Promise<string> {
+ const flow = createMockFlow({ projectId: ctx.project.id })
+ if (isNil(flowId)) {
+ await db.save('flow', flow)
+ }
+ const response = await ctx.post(`/v1/tables/${tableId}/webhooks`, {
+ events: [TableWebhookEventType.RECORD_CREATED],
+ webhookUrl: 'http://localhost:4200/api/v1/webhooks/flow',
+ flowId: flowId ?? flow.id,
+ })
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ return response?.json().id
}