first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,358 @@
|
||||
import type {
|
||||
ICredentialDataDecryptedObject,
|
||||
ICredentialTestFunctions,
|
||||
IDataObject,
|
||||
IExecuteFunctions,
|
||||
ILoadOptionsFunctions,
|
||||
INodeProperties,
|
||||
IPairedItemData,
|
||||
JsonObject,
|
||||
IHttpRequestMethods,
|
||||
IRequestOptions,
|
||||
} from 'n8n-workflow';
|
||||
import { NodeApiError } from 'n8n-workflow';
|
||||
|
||||
export function getSchemaHeader(
|
||||
context: IExecuteFunctions | ILoadOptionsFunctions,
|
||||
method: IHttpRequestMethods,
|
||||
contextType: 'execute' | 'loadOptions',
|
||||
) {
|
||||
let useCustomSchema = false;
|
||||
|
||||
if (contextType === 'loadOptions') {
|
||||
useCustomSchema = context.getNodeParameter('useCustomSchema', false) as boolean;
|
||||
} else {
|
||||
useCustomSchema = context.getNodeParameter('useCustomSchema', 0, false) as boolean;
|
||||
}
|
||||
|
||||
if (useCustomSchema) {
|
||||
let schema: string;
|
||||
const headers: IDataObject = {};
|
||||
|
||||
if (contextType === 'loadOptions') {
|
||||
schema = context.getNodeParameter('schema', 'public') as string;
|
||||
} else {
|
||||
schema = context.getNodeParameter('schema', 0, 'public') as string;
|
||||
}
|
||||
|
||||
if (['POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
|
||||
headers['Content-Profile'] = schema;
|
||||
} else if (['GET', 'HEAD'].includes(method)) {
|
||||
headers['Accept-Profile'] = schema;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
export async function supabaseApiRequest(
|
||||
this: IExecuteFunctions | ILoadOptionsFunctions,
|
||||
method: IHttpRequestMethods,
|
||||
resource: string,
|
||||
body: IDataObject | IDataObject[] = {},
|
||||
qs: IDataObject = {},
|
||||
uri?: string,
|
||||
headers: IDataObject = {},
|
||||
) {
|
||||
const credentials = await this.getCredentials<{
|
||||
host: string;
|
||||
serviceRole: string;
|
||||
}>('supabaseApi');
|
||||
|
||||
const options: IRequestOptions = {
|
||||
headers: {
|
||||
Prefer: 'return=representation',
|
||||
},
|
||||
method,
|
||||
qs,
|
||||
body,
|
||||
uri: uri ?? `${credentials.host}/rest/v1${resource}`,
|
||||
json: true,
|
||||
};
|
||||
|
||||
try {
|
||||
options.headers = Object.assign({}, options.headers, headers);
|
||||
if (Object.keys(body).length === 0) {
|
||||
delete options.body;
|
||||
}
|
||||
return await this.helpers.requestWithAuthentication.call(this, 'supabaseApi', options);
|
||||
} catch (error) {
|
||||
if (error.description) {
|
||||
error.message = `${error.message}: ${error.description}`;
|
||||
}
|
||||
throw new NodeApiError(this.getNode(), error as JsonObject);
|
||||
}
|
||||
}
|
||||
|
||||
const mapOperations: { [key: string]: string } = {
|
||||
create: 'created',
|
||||
update: 'updated',
|
||||
getAll: 'retrieved',
|
||||
delete: 'deleted',
|
||||
};
|
||||
|
||||
export function getFilters(
|
||||
resources: string[],
|
||||
operations: string[],
|
||||
{
|
||||
includeNoneOption = true,
|
||||
filterTypeDisplayName = 'Filter',
|
||||
filterFixedCollectionDisplayName = 'Filters',
|
||||
|
||||
mustMatchOptions = [
|
||||
{
|
||||
name: 'Any Filter',
|
||||
value: 'anyFilter',
|
||||
},
|
||||
{
|
||||
name: 'All Filters',
|
||||
value: 'allFilters',
|
||||
},
|
||||
],
|
||||
},
|
||||
): INodeProperties[] {
|
||||
return [
|
||||
{
|
||||
displayName: filterTypeDisplayName,
|
||||
name: 'filterType',
|
||||
type: 'options',
|
||||
options: [
|
||||
...(includeNoneOption ? [{ name: 'None', value: 'none' }] : []),
|
||||
{
|
||||
name: 'Build Manually',
|
||||
value: 'manual',
|
||||
},
|
||||
{
|
||||
name: 'String',
|
||||
value: 'string',
|
||||
},
|
||||
],
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: resources,
|
||||
operation: operations,
|
||||
},
|
||||
},
|
||||
default: 'manual',
|
||||
},
|
||||
{
|
||||
displayName: 'Must Match',
|
||||
name: 'matchType',
|
||||
type: 'options',
|
||||
options: mustMatchOptions,
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: resources,
|
||||
operation: operations,
|
||||
filterType: ['manual'],
|
||||
},
|
||||
},
|
||||
default: 'anyFilter',
|
||||
},
|
||||
{
|
||||
displayName: filterFixedCollectionDisplayName,
|
||||
name: 'filters',
|
||||
type: 'fixedCollection',
|
||||
typeOptions: {
|
||||
multipleValues: true,
|
||||
},
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: resources,
|
||||
operation: operations,
|
||||
filterType: ['manual'],
|
||||
},
|
||||
},
|
||||
default: {},
|
||||
placeholder: 'Add Condition',
|
||||
options: [
|
||||
{
|
||||
displayName: 'Conditions',
|
||||
name: 'conditions',
|
||||
values: [
|
||||
{
|
||||
displayName: 'Field Name or ID',
|
||||
name: 'keyName',
|
||||
type: 'options',
|
||||
description:
|
||||
'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
|
||||
typeOptions: {
|
||||
loadOptionsDependsOn: ['tableId'],
|
||||
loadOptionsMethod: 'getTableColumns',
|
||||
},
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Condition',
|
||||
name: 'condition',
|
||||
type: 'options',
|
||||
options: [
|
||||
{
|
||||
name: 'Equals',
|
||||
value: 'eq',
|
||||
},
|
||||
{
|
||||
name: 'Full-Text',
|
||||
value: 'fullText',
|
||||
},
|
||||
{
|
||||
name: 'Greater Than',
|
||||
value: 'gt',
|
||||
},
|
||||
{
|
||||
name: 'Greater Than or Equal',
|
||||
value: 'gte',
|
||||
},
|
||||
{
|
||||
name: 'ILIKE operator',
|
||||
value: 'ilike',
|
||||
description: 'Use * in place of %',
|
||||
},
|
||||
{
|
||||
name: 'Is',
|
||||
value: 'is',
|
||||
description: 'Checking for exact equality (null,true,false,unknown)',
|
||||
},
|
||||
{
|
||||
name: 'Less Than',
|
||||
value: 'lt',
|
||||
},
|
||||
{
|
||||
name: 'Less Than or Equal',
|
||||
value: 'lte',
|
||||
},
|
||||
{
|
||||
name: 'LIKE operator',
|
||||
value: 'like',
|
||||
description: 'Use * in place of %',
|
||||
},
|
||||
{
|
||||
name: 'Not Equals',
|
||||
value: 'neq',
|
||||
},
|
||||
],
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Search Function',
|
||||
name: 'searchFunction',
|
||||
type: 'options',
|
||||
displayOptions: {
|
||||
show: {
|
||||
condition: ['fullText'],
|
||||
},
|
||||
},
|
||||
options: [
|
||||
{
|
||||
name: 'to_tsquery',
|
||||
value: 'fts',
|
||||
},
|
||||
{
|
||||
name: 'plainto_tsquery',
|
||||
value: 'plfts',
|
||||
},
|
||||
{
|
||||
name: 'phraseto_tsquery',
|
||||
value: 'phfts',
|
||||
},
|
||||
{
|
||||
name: 'websearch_to_tsquery',
|
||||
value: 'wfts',
|
||||
},
|
||||
],
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Field Value',
|
||||
name: 'keyValue',
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
description: `Filter to decide which rows get ${mapOperations[operations[0]]}`,
|
||||
},
|
||||
{
|
||||
displayName:
|
||||
'See <a href="https://postgrest.org/en/stable/references/api/tables_views.html#horizontal-filtering" target="_blank">PostgREST guide</a> to creating filters',
|
||||
name: 'jsonNotice',
|
||||
type: 'notice',
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: resources,
|
||||
operation: operations,
|
||||
filterType: ['string'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Filters (String)',
|
||||
name: 'filterString',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: resources,
|
||||
operation: operations,
|
||||
filterType: ['string'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: 'name=eq.jhon',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export const buildQuery = (obj: IDataObject, value: IDataObject) => {
|
||||
if (value.condition === 'fullText') {
|
||||
return Object.assign(obj, {
|
||||
[`${value.keyName}`]: `${value.searchFunction}.${value.keyValue}`,
|
||||
});
|
||||
}
|
||||
return Object.assign(obj, { [`${value.keyName}`]: `${value.condition}.${value.keyValue}` });
|
||||
};
|
||||
|
||||
export const buildOrQuery = (key: IDataObject) => {
|
||||
if (key.condition === 'fullText') {
|
||||
return `${key.keyName}.${key.searchFunction}.${key.keyValue}`;
|
||||
}
|
||||
return `${key.keyName}.${key.condition}.${key.keyValue}`;
|
||||
};
|
||||
|
||||
export const buildGetQuery = (obj: IDataObject, value: IDataObject) => {
|
||||
return Object.assign(obj, { [`${value.keyName}`]: `eq.${value.keyValue}` });
|
||||
};
|
||||
|
||||
export async function validateCredentials(
|
||||
this: ICredentialTestFunctions,
|
||||
decryptedCredentials: ICredentialDataDecryptedObject,
|
||||
): Promise<any> {
|
||||
const credentials = decryptedCredentials;
|
||||
|
||||
const { serviceRole } = credentials as {
|
||||
serviceRole: string;
|
||||
};
|
||||
|
||||
const options: IRequestOptions = {
|
||||
headers: {
|
||||
apikey: serviceRole,
|
||||
Authorization: 'Bearer ' + serviceRole,
|
||||
},
|
||||
method: 'GET',
|
||||
uri: `${credentials.host}/rest/v1/`,
|
||||
json: true,
|
||||
};
|
||||
|
||||
return await this.helpers.request(options);
|
||||
}
|
||||
|
||||
export function mapPairedItemsFrom<T>(iterable: Iterable<T> | ArrayLike<T>): IPairedItemData[] {
|
||||
return Array.from(iterable, (_, i) => i).map((index) => {
|
||||
return {
|
||||
item: index,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
import { getFilters } from './GenericFunctions';
|
||||
|
||||
export const rowOperations: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Operation',
|
||||
name: 'operation',
|
||||
type: 'options',
|
||||
noDataExpression: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
},
|
||||
},
|
||||
options: [
|
||||
{
|
||||
name: 'Create',
|
||||
value: 'create',
|
||||
description: 'Create a new row',
|
||||
action: 'Create a row',
|
||||
},
|
||||
{
|
||||
name: 'Delete',
|
||||
value: 'delete',
|
||||
description: 'Delete a row',
|
||||
action: 'Delete a row',
|
||||
},
|
||||
{
|
||||
name: 'Get',
|
||||
value: 'get',
|
||||
description: 'Get a row',
|
||||
action: 'Get a row',
|
||||
},
|
||||
{
|
||||
name: 'Get Many',
|
||||
value: 'getAll',
|
||||
description: 'Get many rows',
|
||||
action: 'Get many rows',
|
||||
},
|
||||
{
|
||||
name: 'Update',
|
||||
value: 'update',
|
||||
description: 'Update a row',
|
||||
action: 'Update a row',
|
||||
},
|
||||
],
|
||||
default: 'create',
|
||||
},
|
||||
];
|
||||
|
||||
export const rowFields: INodeProperties[] = [
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* row:create */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
{
|
||||
displayName: 'Table Name or ID',
|
||||
name: 'tableId',
|
||||
type: 'options',
|
||||
description:
|
||||
'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
|
||||
typeOptions: {
|
||||
loadOptionsDependsOn: ['useCustomSchema', 'schema'],
|
||||
loadOptionsMethod: 'getTables',
|
||||
},
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['create', 'delete', 'get', 'getAll', 'update'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
},
|
||||
...getFilters(['row'], ['update'], {
|
||||
includeNoneOption: false,
|
||||
filterTypeDisplayName: 'Select Type',
|
||||
filterFixedCollectionDisplayName: 'Select Conditions',
|
||||
mustMatchOptions: [
|
||||
{
|
||||
name: 'Any Select Condition',
|
||||
value: 'anyFilter',
|
||||
},
|
||||
{
|
||||
name: 'All Select Conditions',
|
||||
value: 'allFilters',
|
||||
},
|
||||
],
|
||||
}),
|
||||
{
|
||||
displayName: 'Data to Send',
|
||||
name: 'dataToSend',
|
||||
type: 'options',
|
||||
options: [
|
||||
{
|
||||
name: 'Auto-Map Input Data to Columns',
|
||||
value: 'autoMapInputData',
|
||||
description: 'Use when node input properties match destination column names',
|
||||
},
|
||||
{
|
||||
name: 'Define Below for Each Column',
|
||||
value: 'defineBelow',
|
||||
description: 'Set the value for each destination column',
|
||||
},
|
||||
],
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['create', 'update'],
|
||||
},
|
||||
},
|
||||
default: 'defineBelow',
|
||||
},
|
||||
{
|
||||
displayName: 'Inputs to Ignore',
|
||||
name: 'inputsToIgnore',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['create', 'update'],
|
||||
dataToSend: ['autoMapInputData'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
description:
|
||||
'List of input properties to avoid sending, separated by commas. Leave empty to send all properties.',
|
||||
placeholder: 'Enter properties...',
|
||||
},
|
||||
{
|
||||
displayName: 'Fields to Send',
|
||||
name: 'fieldsUi',
|
||||
placeholder: 'Add Field',
|
||||
type: 'fixedCollection',
|
||||
typeOptions: {
|
||||
multipleValueButtonText: 'Add Field to Send',
|
||||
multipleValues: true,
|
||||
},
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['create', 'update'],
|
||||
dataToSend: ['defineBelow'],
|
||||
},
|
||||
},
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Field',
|
||||
name: 'fieldValues',
|
||||
values: [
|
||||
{
|
||||
displayName: 'Field Name or ID',
|
||||
name: 'fieldId',
|
||||
type: 'options',
|
||||
description:
|
||||
'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
|
||||
typeOptions: {
|
||||
loadOptionsDependsOn: ['tableId'],
|
||||
loadOptionsMethod: 'getTableColumns',
|
||||
},
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Field Value',
|
||||
name: 'fieldValue',
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* row:delete */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
...getFilters(['row'], ['delete'], {
|
||||
includeNoneOption: false,
|
||||
filterTypeDisplayName: 'Select Type',
|
||||
filterFixedCollectionDisplayName: 'Select Conditions',
|
||||
mustMatchOptions: [
|
||||
{
|
||||
name: 'Any Select Condition',
|
||||
value: 'anyFilter',
|
||||
},
|
||||
{
|
||||
name: 'All Select Conditions',
|
||||
value: 'allFilters',
|
||||
},
|
||||
],
|
||||
}),
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* row:get */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
{
|
||||
displayName: 'Select Conditions',
|
||||
name: 'filters',
|
||||
type: 'fixedCollection',
|
||||
typeOptions: {
|
||||
multipleValues: true,
|
||||
},
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['get'],
|
||||
},
|
||||
},
|
||||
default: {},
|
||||
placeholder: 'Add Condition',
|
||||
options: [
|
||||
{
|
||||
displayName: 'Conditions',
|
||||
name: 'conditions',
|
||||
values: [
|
||||
{
|
||||
displayName: 'Name or ID',
|
||||
name: 'keyName',
|
||||
type: 'options',
|
||||
typeOptions: {
|
||||
loadOptionsDependsOn: ['tableId'],
|
||||
loadOptionsMethod: 'getTableColumns',
|
||||
},
|
||||
default: '',
|
||||
description:
|
||||
'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
|
||||
},
|
||||
{
|
||||
displayName: 'Value',
|
||||
name: 'keyValue',
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* row:getAll */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
{
|
||||
displayName: 'Return All',
|
||||
name: 'returnAll',
|
||||
type: 'boolean',
|
||||
noDataExpression: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['getAll'],
|
||||
},
|
||||
},
|
||||
default: false,
|
||||
description: 'Whether to return all results or only up to a given limit',
|
||||
},
|
||||
{
|
||||
displayName: 'Limit',
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
displayOptions: {
|
||||
show: {
|
||||
resource: ['row'],
|
||||
operation: ['getAll'],
|
||||
returnAll: [false],
|
||||
},
|
||||
},
|
||||
typeOptions: {
|
||||
minValue: 1,
|
||||
},
|
||||
default: 50,
|
||||
description: 'Max number of results to return',
|
||||
},
|
||||
...getFilters(['row'], ['getAll'], {}),
|
||||
];
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"node": "n8n-nodes-base.supabase",
|
||||
"nodeVersion": "1.0",
|
||||
"codexVersion": "1.0",
|
||||
"categories": ["Data & Storage"],
|
||||
"resources": {
|
||||
"credentialDocumentation": [
|
||||
{
|
||||
"url": "https://docs.n8n.io/integrations/builtin/credentials/supabase/"
|
||||
}
|
||||
],
|
||||
"primaryDocumentation": [
|
||||
{
|
||||
"url": "https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.supabase/"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
import type {
|
||||
IExecuteFunctions,
|
||||
ICredentialDataDecryptedObject,
|
||||
ICredentialsDecrypted,
|
||||
ICredentialTestFunctions,
|
||||
IDataObject,
|
||||
ILoadOptionsFunctions,
|
||||
INodeCredentialTestResult,
|
||||
INodeExecutionData,
|
||||
INodePropertyOptions,
|
||||
INodeType,
|
||||
INodeTypeDescription,
|
||||
} from 'n8n-workflow';
|
||||
import { NodeConnectionTypes, NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import {
|
||||
buildGetQuery,
|
||||
buildOrQuery,
|
||||
buildQuery,
|
||||
getSchemaHeader,
|
||||
mapPairedItemsFrom,
|
||||
supabaseApiRequest,
|
||||
validateCredentials,
|
||||
} from './GenericFunctions';
|
||||
import { rowFields, rowOperations } from './RowDescription';
|
||||
|
||||
export type FieldsUiValues = Array<{
|
||||
fieldId: string;
|
||||
fieldValue: string;
|
||||
}>;
|
||||
|
||||
export class Supabase implements INodeType {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'Supabase',
|
||||
name: 'supabase',
|
||||
icon: 'file:supabase.svg',
|
||||
group: ['input'],
|
||||
version: 1,
|
||||
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
|
||||
description: 'Add, get, delete and update data in a table',
|
||||
defaults: {
|
||||
name: 'Supabase',
|
||||
},
|
||||
inputs: [NodeConnectionTypes.Main],
|
||||
outputs: [NodeConnectionTypes.Main],
|
||||
usableAsTool: true,
|
||||
credentials: [
|
||||
{
|
||||
name: 'supabaseApi',
|
||||
required: true,
|
||||
testedBy: 'supabaseApiCredentialTest',
|
||||
},
|
||||
],
|
||||
hints: [
|
||||
{
|
||||
type: 'info',
|
||||
message:
|
||||
'Note on using an expression for Schema: It will be evaluated only once, so all items will use the <em>same</em> document. It will be calculated by evaluating the expression for the <strong>first input item</strong>.',
|
||||
displayCondition: '={{ $rawParameter.schema?.startsWith("=") && $input.all().length > 1 }}',
|
||||
whenToDisplay: 'always',
|
||||
location: 'outputPane',
|
||||
},
|
||||
],
|
||||
properties: [
|
||||
{
|
||||
displayName: 'Use Custom Schema',
|
||||
name: 'useCustomSchema',
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
noDataExpression: true,
|
||||
description:
|
||||
'Whether to use a database schema different from the default "public" schema (requires schema exposure in the <a href="https://supabase.com/docs/guides/api/using-custom-schemas?queryGroups=language&language=curl#exposing-custom-schemas">Supabase API</a>)',
|
||||
},
|
||||
{
|
||||
displayName: 'Schema',
|
||||
name: 'schema',
|
||||
type: 'string',
|
||||
default: 'public',
|
||||
description: 'Name of database schema to use for table',
|
||||
noDataExpression: false,
|
||||
displayOptions: { show: { useCustomSchema: [true] } },
|
||||
},
|
||||
{
|
||||
displayName: 'Resource',
|
||||
name: 'resource',
|
||||
type: 'options',
|
||||
noDataExpression: true,
|
||||
options: [
|
||||
{
|
||||
name: 'Row',
|
||||
value: 'row',
|
||||
},
|
||||
],
|
||||
default: 'row',
|
||||
},
|
||||
...rowOperations,
|
||||
...rowFields,
|
||||
],
|
||||
};
|
||||
|
||||
methods = {
|
||||
loadOptions: {
|
||||
async getTables(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
|
||||
const returnData: INodePropertyOptions[] = [];
|
||||
const header = getSchemaHeader(this, 'GET', 'loadOptions');
|
||||
const { paths } = await supabaseApiRequest.call(
|
||||
this,
|
||||
'GET',
|
||||
'/',
|
||||
{},
|
||||
{},
|
||||
undefined,
|
||||
header,
|
||||
);
|
||||
for (const path of Object.keys(paths as IDataObject)) {
|
||||
//omit introspection path
|
||||
if (path === '/') continue;
|
||||
returnData.push({
|
||||
name: path.replace('/', ''),
|
||||
value: path.replace('/', ''),
|
||||
});
|
||||
}
|
||||
return returnData;
|
||||
},
|
||||
async getTableColumns(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
|
||||
const returnData: INodePropertyOptions[] = [];
|
||||
const tableName = this.getCurrentNodeParameter('tableId') as string;
|
||||
const header = getSchemaHeader(this, 'GET', 'loadOptions');
|
||||
const { definitions } = await supabaseApiRequest.call(
|
||||
this,
|
||||
'GET',
|
||||
'/',
|
||||
{},
|
||||
{},
|
||||
undefined,
|
||||
header,
|
||||
);
|
||||
for (const column of Object.keys(definitions[tableName].properties as IDataObject)) {
|
||||
returnData.push({
|
||||
name: `${column} - (${definitions[tableName].properties[column].type})`,
|
||||
value: column,
|
||||
});
|
||||
}
|
||||
return returnData;
|
||||
},
|
||||
},
|
||||
credentialTest: {
|
||||
async supabaseApiCredentialTest(
|
||||
this: ICredentialTestFunctions,
|
||||
credential: ICredentialsDecrypted,
|
||||
): Promise<INodeCredentialTestResult> {
|
||||
try {
|
||||
await validateCredentials.call(this, credential.data as ICredentialDataDecryptedObject);
|
||||
} catch (error) {
|
||||
return {
|
||||
status: 'Error',
|
||||
message: 'The Service Key is invalid',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'OK',
|
||||
message: 'Connection successful!',
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
|
||||
const items = this.getInputData();
|
||||
const returnData: INodeExecutionData[] = [];
|
||||
const length = items.length;
|
||||
let qs: IDataObject = {};
|
||||
const resource = this.getNodeParameter('resource', 0);
|
||||
const operation = this.getNodeParameter('operation', 0);
|
||||
|
||||
if (resource === 'row') {
|
||||
const tableId = this.getNodeParameter('tableId', 0) as string;
|
||||
|
||||
if (operation === 'create') {
|
||||
const records: IDataObject[] = [];
|
||||
const header = getSchemaHeader(this, 'POST', 'execute');
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const record: IDataObject = {};
|
||||
const dataToSend = this.getNodeParameter('dataToSend', 0) as
|
||||
| 'defineBelow'
|
||||
| 'autoMapInputData';
|
||||
|
||||
if (dataToSend === 'autoMapInputData') {
|
||||
const incomingKeys = Object.keys(items[i].json);
|
||||
const rawInputsToIgnore = this.getNodeParameter('inputsToIgnore', i) as string;
|
||||
const inputDataToIgnore = rawInputsToIgnore.split(',').map((c) => c.trim());
|
||||
|
||||
for (const key of incomingKeys) {
|
||||
if (inputDataToIgnore.includes(key)) continue;
|
||||
record[key] = items[i].json[key];
|
||||
}
|
||||
} else {
|
||||
const fields = this.getNodeParameter('fieldsUi.fieldValues', i, []) as FieldsUiValues;
|
||||
for (const field of fields) {
|
||||
record[`${field.fieldId}`] = field.fieldValue;
|
||||
}
|
||||
}
|
||||
records.push(record);
|
||||
}
|
||||
const endpoint = `/${tableId}`;
|
||||
|
||||
try {
|
||||
const createdRows: IDataObject[] = await supabaseApiRequest.call(
|
||||
this,
|
||||
'POST',
|
||||
endpoint,
|
||||
records,
|
||||
{},
|
||||
undefined,
|
||||
header,
|
||||
);
|
||||
createdRows.forEach((row, i) => {
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray(row),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray({ error: error.description }),
|
||||
{ itemData: mapPairedItemsFrom(records) },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (operation === 'delete') {
|
||||
const filterType = this.getNodeParameter('filterType', 0) as string;
|
||||
const header = getSchemaHeader(this, 'DELETE', 'execute');
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
let endpoint = `/${tableId}`;
|
||||
if (filterType === 'manual') {
|
||||
const matchType = this.getNodeParameter('matchType', 0) as string;
|
||||
const keys = this.getNodeParameter('filters.conditions', i, []) as IDataObject[];
|
||||
|
||||
if (!keys.length) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
'At least one select condition must be defined',
|
||||
{ itemIndex: i },
|
||||
);
|
||||
}
|
||||
|
||||
if (matchType === 'allFilters') {
|
||||
const data = keys.reduce((obj, value) => buildQuery(obj, value), {});
|
||||
Object.assign(qs, data);
|
||||
}
|
||||
if (matchType === 'anyFilter') {
|
||||
const data = keys.map((key) => buildOrQuery(key));
|
||||
Object.assign(qs, { or: `(${data.join(',')})` });
|
||||
}
|
||||
}
|
||||
|
||||
if (filterType === 'string') {
|
||||
const filterString = this.getNodeParameter('filterString', i) as string;
|
||||
endpoint = `${endpoint}?${encodeURI(filterString)}`;
|
||||
}
|
||||
|
||||
let rows;
|
||||
|
||||
try {
|
||||
rows = await supabaseApiRequest.call(
|
||||
this,
|
||||
'DELETE',
|
||||
endpoint,
|
||||
{},
|
||||
qs,
|
||||
undefined,
|
||||
header,
|
||||
);
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray({ error: error.description }),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray(rows as IDataObject[]),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
}
|
||||
}
|
||||
|
||||
if (operation === 'get') {
|
||||
const endpoint = `/${tableId}`;
|
||||
const header = getSchemaHeader(this, 'GET', 'execute');
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const keys = this.getNodeParameter('filters.conditions', i, []) as IDataObject[];
|
||||
const data = keys.reduce((obj, value) => buildGetQuery(obj, value), {});
|
||||
Object.assign(qs, data);
|
||||
let rows;
|
||||
|
||||
if (!keys.length) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
'At least one select condition must be defined',
|
||||
{ itemIndex: i },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
rows = await supabaseApiRequest.call(this, 'GET', endpoint, {}, qs, undefined, header);
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray({ error: error.message }),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray(rows as IDataObject[]),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
}
|
||||
}
|
||||
|
||||
if (operation === 'getAll') {
|
||||
const returnAll = this.getNodeParameter('returnAll', 0);
|
||||
const filterType = this.getNodeParameter('filterType', 0) as string;
|
||||
const header = getSchemaHeader(this, 'GET', 'execute');
|
||||
|
||||
let endpoint = `/${tableId}`;
|
||||
for (let i = 0; i < length; i++) {
|
||||
qs = {}; // reset qs
|
||||
|
||||
if (filterType === 'manual') {
|
||||
const matchType = this.getNodeParameter('matchType', 0) as string;
|
||||
const keys = this.getNodeParameter('filters.conditions', i, []) as IDataObject[];
|
||||
|
||||
if (keys.length !== 0) {
|
||||
if (matchType === 'allFilters') {
|
||||
const data = keys.map((key) => buildOrQuery(key));
|
||||
Object.assign(qs, { and: `(${data.join(',')})` });
|
||||
}
|
||||
if (matchType === 'anyFilter') {
|
||||
const data = keys.map((key) => buildOrQuery(key));
|
||||
Object.assign(qs, { or: `(${data.join(',')})` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filterType === 'string') {
|
||||
const filterString = this.getNodeParameter('filterString', i) as string;
|
||||
endpoint = `${endpoint}?${encodeURI(filterString)}`;
|
||||
}
|
||||
|
||||
if (!returnAll) {
|
||||
qs.limit = this.getNodeParameter('limit', 0);
|
||||
}
|
||||
|
||||
let rows: IDataObject[] = [];
|
||||
|
||||
try {
|
||||
let responseLength = 0;
|
||||
do {
|
||||
const newRows = await supabaseApiRequest.call(
|
||||
this,
|
||||
'GET',
|
||||
endpoint,
|
||||
{},
|
||||
qs,
|
||||
undefined,
|
||||
header,
|
||||
);
|
||||
responseLength = newRows.length;
|
||||
rows = rows.concat(newRows);
|
||||
qs.offset = rows.length;
|
||||
} while (responseLength >= 1000);
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray(rows),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray({ error: error.description }),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (operation === 'update') {
|
||||
const filterType = this.getNodeParameter('filterType', 0) as string;
|
||||
let endpoint = `/${tableId}`;
|
||||
const header = getSchemaHeader(this, 'PATCH', 'execute');
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (filterType === 'manual') {
|
||||
const matchType = this.getNodeParameter('matchType', 0) as string;
|
||||
const keys = this.getNodeParameter('filters.conditions', i, []) as IDataObject[];
|
||||
|
||||
if (!keys.length) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
'At least one select condition must be defined',
|
||||
{ itemIndex: i },
|
||||
);
|
||||
}
|
||||
|
||||
if (matchType === 'allFilters') {
|
||||
const data = keys.reduce((obj, value) => buildQuery(obj, value), {});
|
||||
Object.assign(qs, data);
|
||||
}
|
||||
if (matchType === 'anyFilter') {
|
||||
const data = keys.map((key) => buildOrQuery(key));
|
||||
Object.assign(qs, { or: `(${data.join(',')})` });
|
||||
}
|
||||
}
|
||||
|
||||
if (filterType === 'string') {
|
||||
const filterString = this.getNodeParameter('filterString', i) as string;
|
||||
endpoint = `${endpoint}?${encodeURI(filterString)}`;
|
||||
}
|
||||
|
||||
const record: IDataObject = {};
|
||||
const dataToSend = this.getNodeParameter('dataToSend', 0) as
|
||||
| 'defineBelow'
|
||||
| 'autoMapInputData';
|
||||
|
||||
if (dataToSend === 'autoMapInputData') {
|
||||
const incomingKeys = Object.keys(items[i].json);
|
||||
const rawInputsToIgnore = this.getNodeParameter('inputsToIgnore', i) as string;
|
||||
const inputDataToIgnore = rawInputsToIgnore.split(',').map((c) => c.trim());
|
||||
|
||||
for (const key of incomingKeys) {
|
||||
if (inputDataToIgnore.includes(key)) continue;
|
||||
record[key] = items[i].json[key];
|
||||
}
|
||||
} else {
|
||||
const fields = this.getNodeParameter('fieldsUi.fieldValues', i, []) as FieldsUiValues;
|
||||
for (const field of fields) {
|
||||
record[`${field.fieldId}`] = field.fieldValue;
|
||||
}
|
||||
}
|
||||
let updatedRow;
|
||||
|
||||
try {
|
||||
updatedRow = await supabaseApiRequest.call(
|
||||
this,
|
||||
'PATCH',
|
||||
endpoint,
|
||||
record,
|
||||
qs,
|
||||
undefined,
|
||||
header,
|
||||
);
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray(updatedRow as IDataObject[]),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
const executionData = this.helpers.constructExecutionMetaData(
|
||||
this.helpers.returnJsonArray({ error: error.description }),
|
||||
{ itemData: { item: i } },
|
||||
);
|
||||
returnData.push(...executionData);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return [returnData];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"created_at": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"type": "string"
|
||||
},
|
||||
"embedding": {
|
||||
"type": "string"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"blobType": {
|
||||
"type": "string"
|
||||
},
|
||||
"file_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"loc": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lines": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"from": {
|
||||
"type": "integer"
|
||||
},
|
||||
"to": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": 2
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"created_at": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"created_at": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"created_at": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="109" height="113" fill="none"><path fill="url(#a)" d="M63.708 110.284c-2.86 3.601-8.658 1.628-8.727-2.97l-1.007-67.251h45.22c8.19 0 12.758 9.46 7.665 15.874z"/><path fill="url(#b)" fill-opacity=".2" d="M63.708 110.284c-2.86 3.601-8.658 1.628-8.727-2.97l-1.007-67.251h45.22c8.19 0 12.758 9.46 7.665 15.874z"/><path fill="#3ECF8E" d="M45.317 2.071c2.86-3.601 8.657-1.628 8.726 2.97l.442 67.251H9.83c-8.19 0-12.759-9.46-7.665-15.875z"/><defs><linearGradient id="a" x1="53.974" x2="94.163" y1="54.974" y2="71.829" gradientUnits="userSpaceOnUse"><stop stop-color="#249361"/><stop offset="1" stop-color="#3ECF8E"/></linearGradient><linearGradient id="b" x1="36.156" x2="54.484" y1="30.578" y2="65.081" gradientUnits="userSpaceOnUse"><stop/><stop offset="1" stop-opacity="0"/></linearGradient></defs></svg>
|
||||
|
After Width: | Height: | Size: 846 B |
@@ -0,0 +1,335 @@
|
||||
import { mock } from 'jest-mock-extended';
|
||||
import get from 'lodash/get';
|
||||
import {
|
||||
type IDataObject,
|
||||
type IExecuteFunctions,
|
||||
type IGetNodeParameterOptions,
|
||||
type INodeExecutionData,
|
||||
type IPairedItemData,
|
||||
NodeOperationError,
|
||||
} from 'n8n-workflow';
|
||||
|
||||
import * as utils from '../GenericFunctions';
|
||||
import { Supabase } from '../Supabase.node';
|
||||
|
||||
describe('Test Supabase Node', () => {
|
||||
const node = new Supabase();
|
||||
const input = [{ json: {} }];
|
||||
const mockRequestWithAuthentication = jest.fn().mockResolvedValue([]);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
const createMockExecuteFunction = (
|
||||
nodeParameters: IDataObject,
|
||||
continueOnFail: boolean = false,
|
||||
) => {
|
||||
const fakeExecuteFunction = {
|
||||
getCredentials: jest.fn().mockResolvedValue({
|
||||
host: 'https://api.supabase.io',
|
||||
serviceRole: 'service_role',
|
||||
}),
|
||||
getNodeParameter(
|
||||
parameterName: string,
|
||||
itemIndex: number,
|
||||
fallbackValue?: IDataObject,
|
||||
options?: IGetNodeParameterOptions,
|
||||
) {
|
||||
const parameter = options?.extractValue ? `${parameterName}.value` : parameterName;
|
||||
const parameterValue = get(nodeParameters, parameter, fallbackValue);
|
||||
if ((parameterValue as IDataObject)?.nodeOperationError) {
|
||||
throw new NodeOperationError(mock(), 'Get Options Error', { itemIndex });
|
||||
}
|
||||
return parameterValue;
|
||||
},
|
||||
getNode() {
|
||||
return node;
|
||||
},
|
||||
continueOnFail: () => continueOnFail,
|
||||
getInputData: () => input,
|
||||
helpers: {
|
||||
requestWithAuthentication: mockRequestWithAuthentication,
|
||||
constructExecutionMetaData: (
|
||||
_inputData: INodeExecutionData[],
|
||||
_options: { itemData: IPairedItemData | IPairedItemData[] },
|
||||
) => [],
|
||||
returnJsonArray: (_jsonData: IDataObject | IDataObject[]) => [],
|
||||
},
|
||||
} as unknown as IExecuteFunctions;
|
||||
return fakeExecuteFunction;
|
||||
};
|
||||
|
||||
it('should allow filtering on the same field multiple times', async () => {
|
||||
const supabaseApiRequest = jest
|
||||
.spyOn(utils, 'supabaseApiRequest')
|
||||
.mockImplementation(async () => {
|
||||
return [];
|
||||
});
|
||||
|
||||
const fakeExecuteFunction = createMockExecuteFunction({
|
||||
resource: 'row',
|
||||
operation: 'getAll',
|
||||
returnAll: true,
|
||||
filterType: 'manual',
|
||||
matchType: 'allFilters',
|
||||
tableId: 'my_table',
|
||||
filters: {
|
||||
conditions: [
|
||||
{
|
||||
condition: 'gt',
|
||||
keyName: 'created_at',
|
||||
keyValue: '2025-01-02 08:03:43.952051+00',
|
||||
},
|
||||
{
|
||||
condition: 'lt',
|
||||
keyName: 'created_at',
|
||||
keyValue: '2025-01-02 08:07:36.102231+00',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await node.execute.call(fakeExecuteFunction);
|
||||
|
||||
expect(supabaseApiRequest).toHaveBeenCalledWith(
|
||||
'GET',
|
||||
'/my_table',
|
||||
{},
|
||||
{
|
||||
and: '(created_at.gt.2025-01-02 08:03:43.952051+00,created_at.lt.2025-01-02 08:07:36.102231+00)',
|
||||
offset: 0,
|
||||
},
|
||||
undefined,
|
||||
{},
|
||||
);
|
||||
|
||||
supabaseApiRequest.mockRestore();
|
||||
});
|
||||
|
||||
it('should not set schema headers if no custom schema is used', async () => {
|
||||
const fakeExecuteFunction = createMockExecuteFunction({
|
||||
resource: 'row',
|
||||
operation: 'getAll',
|
||||
returnAll: true,
|
||||
useCustomSchema: false,
|
||||
schema: 'public',
|
||||
tableId: 'my_table',
|
||||
});
|
||||
|
||||
await node.execute.call(fakeExecuteFunction);
|
||||
|
||||
expect(mockRequestWithAuthentication).toHaveBeenCalledWith(
|
||||
'supabaseApi',
|
||||
expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
Prefer: 'return=representation',
|
||||
}),
|
||||
uri: 'https://api.supabase.io/rest/v1/my_table',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should set the schema headers for GET calls if custom schema is used', async () => {
|
||||
const fakeExecuteFunction = createMockExecuteFunction({
|
||||
resource: 'row',
|
||||
operation: 'getAll',
|
||||
returnAll: true,
|
||||
useCustomSchema: true,
|
||||
schema: 'custom_schema',
|
||||
tableId: 'my_table',
|
||||
});
|
||||
|
||||
await node.execute.call(fakeExecuteFunction);
|
||||
|
||||
expect(mockRequestWithAuthentication).toHaveBeenCalledWith(
|
||||
'supabaseApi',
|
||||
expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
'Accept-Profile': 'custom_schema',
|
||||
Prefer: 'return=representation',
|
||||
}),
|
||||
uri: 'https://api.supabase.io/rest/v1/my_table',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should set the schema headers for POST calls if custom schema is used', async () => {
|
||||
const fakeExecuteFunction = createMockExecuteFunction({
|
||||
resource: 'row',
|
||||
operation: 'create',
|
||||
returnAll: true,
|
||||
useCustomSchema: true,
|
||||
schema: 'custom_schema',
|
||||
tableId: 'my_table',
|
||||
dataToSend: 'defineBelow',
|
||||
fieldsUi: {
|
||||
fieldValues: [],
|
||||
},
|
||||
});
|
||||
|
||||
await node.execute.call(fakeExecuteFunction);
|
||||
|
||||
expect(mockRequestWithAuthentication).toHaveBeenCalledWith(
|
||||
'supabaseApi',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: expect.objectContaining({
|
||||
'Content-Profile': 'custom_schema',
|
||||
Prefer: 'return=representation',
|
||||
}),
|
||||
uri: 'https://api.supabase.io/rest/v1/my_table',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should show descriptive message when error is caught', async () => {
|
||||
const fakeExecuteFunction = createMockExecuteFunction({
|
||||
resource: 'row',
|
||||
operation: 'create',
|
||||
returnAll: true,
|
||||
useCustomSchema: true,
|
||||
schema: '',
|
||||
tableId: 'my_table',
|
||||
dataToSend: 'defineBelow',
|
||||
fieldsUi: {
|
||||
fieldValues: [],
|
||||
},
|
||||
});
|
||||
|
||||
fakeExecuteFunction.helpers.requestWithAuthentication = jest.fn().mockRejectedValue({
|
||||
description: 'Something when wrong',
|
||||
message: 'error',
|
||||
});
|
||||
|
||||
await expect(node.execute.call(fakeExecuteFunction)).rejects.toHaveProperty(
|
||||
'message',
|
||||
'error: Something when wrong',
|
||||
);
|
||||
});
|
||||
|
||||
describe('getSchemaHeader function', () => {
|
||||
const mockExecuteContext = {
|
||||
getNodeParameter: jest.fn(),
|
||||
} as unknown as IExecuteFunctions;
|
||||
|
||||
const mockLoadOptionsContext = {
|
||||
getNodeParameter: jest.fn(),
|
||||
} as unknown as any;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should return empty object when useCustomSchema is false for execute context', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock).mockReturnValueOnce(false);
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'GET', 'execute');
|
||||
|
||||
expect(result).toEqual({});
|
||||
expect(mockExecuteContext.getNodeParameter).toHaveBeenCalledWith('useCustomSchema', 0, false);
|
||||
});
|
||||
|
||||
it('should return empty object when useCustomSchema is false for loadOptions context', () => {
|
||||
(mockLoadOptionsContext.getNodeParameter as jest.Mock).mockReturnValueOnce(false);
|
||||
|
||||
const result = utils.getSchemaHeader(mockLoadOptionsContext, 'GET', 'loadOptions');
|
||||
|
||||
expect(result).toEqual({});
|
||||
expect(mockLoadOptionsContext.getNodeParameter).toHaveBeenCalledWith(
|
||||
'useCustomSchema',
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return Accept-Profile header for GET method when useCustomSchema is true', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('custom_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'GET', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Accept-Profile': 'custom_schema' });
|
||||
expect(mockExecuteContext.getNodeParameter).toHaveBeenCalledWith('useCustomSchema', 0, false);
|
||||
expect(mockExecuteContext.getNodeParameter).toHaveBeenCalledWith('schema', 0, 'public');
|
||||
});
|
||||
|
||||
it('should return Accept-Profile header for HEAD method when useCustomSchema is true', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('test_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'HEAD', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Accept-Profile': 'test_schema' });
|
||||
});
|
||||
|
||||
it('should return Content-Profile header for POST method when useCustomSchema is true', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('custom_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'POST', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Content-Profile': 'custom_schema' });
|
||||
});
|
||||
|
||||
it('should return Content-Profile header for PATCH method when useCustomSchema is true', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('custom_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'PATCH', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Content-Profile': 'custom_schema' });
|
||||
});
|
||||
|
||||
it('should return Content-Profile header for PUT method when useCustomSchema is true', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('custom_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'PUT', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Content-Profile': 'custom_schema' });
|
||||
});
|
||||
|
||||
it('should return Content-Profile header for DELETE method when useCustomSchema is true', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('custom_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'DELETE', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Content-Profile': 'custom_schema' });
|
||||
});
|
||||
|
||||
it('should use different parameter calls for loadOptions context', () => {
|
||||
(mockLoadOptionsContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('load_options_schema');
|
||||
|
||||
const result = utils.getSchemaHeader(mockLoadOptionsContext, 'GET', 'loadOptions');
|
||||
|
||||
expect(result).toEqual({ 'Accept-Profile': 'load_options_schema' });
|
||||
expect(mockLoadOptionsContext.getNodeParameter).toHaveBeenCalledWith(
|
||||
'useCustomSchema',
|
||||
false,
|
||||
);
|
||||
expect(mockLoadOptionsContext.getNodeParameter).toHaveBeenCalledWith('schema', 'public');
|
||||
});
|
||||
|
||||
it('should default to public schema when schema parameter is not provided', () => {
|
||||
(mockExecuteContext.getNodeParameter as jest.Mock)
|
||||
.mockReturnValueOnce(true)
|
||||
.mockReturnValueOnce('public');
|
||||
|
||||
const result = utils.getSchemaHeader(mockExecuteContext, 'GET', 'execute');
|
||||
|
||||
expect(result).toEqual({ 'Accept-Profile': 'public' });
|
||||
expect(mockExecuteContext.getNodeParameter).toHaveBeenCalledWith('schema', 0, 'public');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user