Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(Peekalink Node): Stricter typing for Peekalink api call + Tests (no-changelog) #8125

Merged
merged 1 commit into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/nodes-base/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,5 +151,11 @@ module.exports = {
'n8n-nodes-base/node-param-type-options-password-missing': 'error',
},
},
{
files: ['**/*.test.ts', '**/test/**/*.ts'],
rules: {
'import/no-extraneous-dependencies': 'off',
},
},
],
};
41 changes: 0 additions & 41 deletions packages/nodes-base/nodes/Peekalink/GenericFunctions.ts

This file was deleted.

80 changes: 35 additions & 45 deletions packages/nodes-base/nodes/Peekalink/Peekalink.node.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import type {
IExecuteFunctions,
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
import {
Node,
NodeApiError,
type IExecuteFunctions,
type INodeExecutionData,
type INodeTypeDescription,
type JsonObject,
} from 'n8n-workflow';

import { peekalinkApiRequest } from './GenericFunctions';
export const apiUrl = 'https://api.peekalink.io';

export class Peekalink implements INodeType {
type Operation = 'preview' | 'isAvailable';

export class Peekalink extends Node {
description: INodeTypeDescription = {
displayName: 'Peekalink',
name: 'peekalink',
Expand Down Expand Up @@ -61,44 +64,31 @@ export class Peekalink implements INodeType {
],
};

async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = items.length;
let responseData;
const operation = this.getNodeParameter('operation', 0);

for (let i = 0; i < length; i++) {
try {
if (operation === 'isAvailable') {
const url = this.getNodeParameter('url', i) as string;
const body: IDataObject = {
link: url,
};

responseData = await peekalinkApiRequest.call(this, 'POST', '/is-available/', body);
}
if (operation === 'preview') {
const url = this.getNodeParameter('url', i) as string;
const body: IDataObject = {
link: url,
};
async execute(context: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = context.getInputData();
const operation = context.getNodeParameter('operation', 0) as Operation;
const credentials = await context.getCredentials('peekalinkApi');

responseData = await peekalinkApiRequest.call(this, 'POST', '/', body);
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else {
returnData.push(responseData as IDataObject);
}
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
const returnData = await Promise.all(
items.map(async (_, i) => {
try {
const link = context.getNodeParameter('url', i) as string;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await context.helpers.request({
method: 'POST',
uri: operation === 'preview' ? apiUrl : `${apiUrl}/is-available/`,
body: { link },
headers: { 'X-API-Key': credentials.apiKey },
json: true,
});
} catch (error) {
if (context.continueOnFail()) {
return { error: error.message };
}
throw new NodeApiError(context.getNode(), error as JsonObject);
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}),
);
return [context.helpers.returnJsonArray(returnData)];
}
}
171 changes: 171 additions & 0 deletions packages/nodes-base/nodes/Peekalink/test/Peekalink.node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { apiUrl } from '../Peekalink.node';
import type { WorkflowTestData } from '@test/nodes/types';
import { executeWorkflow } from '@test/nodes/ExecuteWorkflow';
import * as Helpers from '@test/nodes/Helpers';

describe('Peekalink Node', () => {
const exampleComPreview = {
url: 'https://example.com/',
domain: 'example.com',
lastUpdated: '2022-11-13T22:43:20.986744Z',
nextUpdate: '2022-11-20T22:43:20.982384Z',
contentType: 'html',
mimeType: 'text/html',
size: 648,
redirected: false,
title: 'Example Domain',
description: 'This domain is for use in illustrative examples in documents',
name: 'EXAMPLE.COM',
trackersDetected: false,
};

const tests: WorkflowTestData[] = [
{
description: 'should run isAvailable operation',
input: {
workflowData: {
nodes: [
{
parameters: {},
id: '8b7bb389-e4ef-424a-bca1-e7ead60e43eb',
name: 'When clicking "Execute Workflow"',
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
position: [740, 380],
},
{
parameters: {
operation: 'isAvailable',
url: 'https://example.com/',
},
id: '7354367e-39a7-4fc1-8cdd-442f0b0c7b62',
name: 'Peekalink',
type: 'n8n-nodes-base.peekalink',
typeVersion: 1,
position: [960, 380],
credentials: {
peekalinkApi: 'token',
},
},
],
connections: {
'When clicking "Execute Workflow"': {
main: [
[
{
node: 'Peekalink',
type: 'main',
index: 0,
},
],
],
},
},
},
},
output: {
nodeExecutionOrder: ['Start'],
nodeData: {
Peekalink: [
[
{
json: {
isAvailable: true,
},
},
],
],
},
},
nock: {
baseUrl: apiUrl,
mocks: [
{
method: 'post',
path: '/is-available/',
statusCode: 200,
responseBody: { isAvailable: true },
},
],
},
},
{
description: 'should run preview operation',
input: {
workflowData: {
nodes: [
{
parameters: {},
id: '8b7bb389-e4ef-424a-bca1-e7ead60e43eb',
name: 'When clicking "Execute Workflow"',
type: 'n8n-nodes-base.manualTrigger',
typeVersion: 1,
position: [740, 380],
},
{
parameters: {
operation: 'preview',
url: 'https://example.com/',
},
id: '7354367e-39a7-4fc1-8cdd-442f0b0c7b62',
name: 'Peekalink',
type: 'n8n-nodes-base.peekalink',
typeVersion: 1,
position: [960, 380],
credentials: {
peekalinkApi: 'token',
},
},
],
connections: {
'When clicking "Execute Workflow"': {
main: [
[
{
node: 'Peekalink',
type: 'main',
index: 0,
},
],
],
},
},
},
},
output: {
nodeExecutionOrder: ['Start'],
nodeData: {
Peekalink: [
[
{
json: exampleComPreview,
},
],
],
},
},
nock: {
baseUrl: apiUrl,
mocks: [
{
method: 'post',
path: '/',
statusCode: 200,
responseBody: exampleComPreview,
},
],
},
},
];

const nodeTypes = Helpers.setup(tests);

test.each(tests)('$description', async (testData) => {
const { result } = await executeWorkflow(testData, nodeTypes);
const resultNodeData = Helpers.getResultNodeData(result, testData);
resultNodeData.forEach(({ nodeName, resultData }) =>
expect(resultData).toEqual(testData.output.nodeData[nodeName]),
);
expect(result.finished).toEqual(true);
});
});
8 changes: 8 additions & 0 deletions packages/nodes-base/test/nodes/ExecuteWorkflow.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import nock from 'nock';
import { WorkflowExecute } from 'n8n-core';
import type { INodeTypes, IRun, IRunExecutionData } from 'n8n-workflow';
import { createDeferredPromise, Workflow } from 'n8n-workflow';
import * as Helpers from './Helpers';
import type { WorkflowTestData } from './types';

export async function executeWorkflow(testData: WorkflowTestData, nodeTypes: INodeTypes) {
if (testData.nock) {
const { baseUrl, mocks } = testData.nock;
const agent = nock(baseUrl);
mocks.forEach(({ method, path, statusCode, responseBody }) =>
agent[method](path).reply(statusCode, responseBody),
);
}
const executionMode = testData.trigger?.mode ?? 'manual';
const workflowInstance = new Workflow({
id: 'test',
Expand Down
11 changes: 11 additions & 0 deletions packages/nodes-base/test/nodes/Helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readFileSync, readdirSync, mkdtempSync } from 'fs';
import path from 'path';
import { tmpdir } from 'os';
import nock from 'nock';
import { isEmpty } from 'lodash';
import { get } from 'lodash';
import { BinaryDataService, Credentials, constructExecutionMetaData } from 'n8n-core';
Expand Down Expand Up @@ -231,6 +232,16 @@ export function setup(testData: WorkflowTestData[] | WorkflowTestData) {
testData = [testData];
}

if (testData.some((t) => !!t.nock)) {
beforeAll(() => {
nock.disableNetConnect();
});

afterAll(() => {
nock.restore();
});
}

const nodeTypes = new NodeTypes();

const nodes = [...new Set(testData.flatMap((data) => data.input.workflowData.nodes))];
Expand Down
Loading