refactor(core): Use an IoC container to manage singleton classes [Part-1] (no-changelog) (#5509)

* add typedi

* convert ActiveWorkflowRunner into an injectable service

* convert ExternalHooks into an injectable service

* convert InternalHooks into an injectable service

* convert LoadNodesAndCredentials into an injectable service

* convert NodeTypes and CredentialTypes into an injectable service

* convert ActiveExecutions into an injectable service

* convert WaitTracker into an injectable service

* convert Push into an injectable service

* convert ActiveWebhooks and  TestWebhooks into an injectable services

* handle circular references, and log errors when a circular dependency is found
This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2023-02-21 19:21:56 +01:00
committed by GitHub
parent aca94bb995
commit 52f740b9e8
79 changed files with 594 additions and 634 deletions

View File

@@ -6,6 +6,13 @@ import { OFFICIAL_RISKY_NODE_TYPES, NODES_REPORT } from '@/audit/constants';
import { getRiskSection, MOCK_PACKAGE, saveManualTriggerWorkflow } from './utils';
import * as testDb from '../shared/testDb';
import { toReportTitle } from '@/audit/utils';
import { mockInstance } from '../shared/utils';
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
import { NodeTypes } from '@/NodeTypes';
const nodesAndCredentials = mockInstance(LoadNodesAndCredentials);
nodesAndCredentials.getCustomDirectories.mockReturnValue([]);
mockInstance(NodeTypes);
beforeAll(async () => {
await testDb.init();

View File

@@ -2,10 +2,17 @@ import * as Db from '@/Db';
import { Reset } from '@/commands/user-management/reset';
import type { Role } from '@db/entities/Role';
import * as testDb from '../shared/testDb';
import { mockInstance } from '../shared/utils';
import { InternalHooks } from '@/InternalHooks';
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
import { NodeTypes } from '@/NodeTypes';
let globalOwnerRole: Role;
beforeAll(async () => {
mockInstance(InternalHooks);
mockInstance(LoadNodesAndCredentials);
mockInstance(NodeTypes);
await testDb.init();
globalOwnerRole = await testDb.getGlobalOwnerRole();

View File

@@ -20,6 +20,12 @@ import type { Role } from '@db/entities/Role';
import type { AuthAgent } from './shared/types';
import type { InstalledNodes } from '@db/entities/InstalledNodes';
import { COMMUNITY_PACKAGE_VERSION } from './shared/constants';
import { NodeTypes } from '@/NodeTypes';
import { Push } from '@/push';
const mockLoadNodesAndCredentials = utils.mockInstance(LoadNodesAndCredentials);
utils.mockInstance(NodeTypes);
utils.mockInstance(Push);
jest.mock('@/CommunityNodes/helpers', () => {
return {
@@ -213,7 +219,7 @@ test('POST /nodes should allow installing packages that could not be loaded', as
mocked(hasPackageLoaded).mockReturnValueOnce(false);
mocked(checkNpmPackageStatus).mockResolvedValueOnce({ status: 'OK' });
jest.spyOn(LoadNodesAndCredentials(), 'loadNpmModule').mockImplementationOnce(mockedEmptyPackage);
mockLoadNodesAndCredentials.loadNpmModule.mockImplementationOnce(mockedEmptyPackage);
const { statusCode } = await authAgent(ownerShell).post('/nodes').send({
name: utils.installedPackagePayload().packageName,
@@ -267,9 +273,7 @@ test('DELETE /nodes should reject if package is not installed', async () => {
test('DELETE /nodes should uninstall package', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const removeSpy = jest
.spyOn(LoadNodesAndCredentials(), 'removeNpmModule')
.mockImplementationOnce(jest.fn());
const removeSpy = mockLoadNodesAndCredentials.removeNpmModule.mockImplementationOnce(jest.fn());
mocked(findInstalledPackage).mockImplementationOnce(mockedEmptyPackage);
@@ -310,9 +314,8 @@ test('PATCH /nodes reject if package is not installed', async () => {
test('PATCH /nodes should update a package', async () => {
const ownerShell = await testDb.createUserShell(globalOwnerRole);
const updateSpy = jest
.spyOn(LoadNodesAndCredentials(), 'updateNpmModule')
.mockImplementationOnce(mockedEmptyPackage);
const updateSpy =
mockLoadNodesAndCredentials.updateNpmModule.mockImplementationOnce(mockedEmptyPackage);
mocked(findInstalledPackage).mockImplementationOnce(mockedEmptyPackage);

View File

@@ -1,3 +1,4 @@
import { Container } from 'typedi';
import { randomBytes } from 'crypto';
import { existsSync } from 'fs';
@@ -25,14 +26,15 @@ import {
import superagent from 'superagent';
import request from 'supertest';
import { URL } from 'url';
import { mock } from 'jest-mock-extended';
import { DeepPartial } from 'ts-essentials';
import config from '@/config';
import * as Db from '@/Db';
import { WorkflowEntity } from '@db/entities/WorkflowEntity';
import { CredentialTypes } from '@/CredentialTypes';
import { ExternalHooks } from '@/ExternalHooks';
import { InternalHooksManager } from '@/InternalHooksManager';
import { NodeTypes } from '@/NodeTypes';
import * as ActiveWorkflowRunner from '@/ActiveWorkflowRunner';
import { ActiveWorkflowRunner } from '@/ActiveWorkflowRunner';
import { nodesController } from '@/api/nodes.api';
import { workflowsController } from '@/workflows/workflows.controller';
import { AUTH_COOKIE_NAME, NODE_PACKAGE_PREFIX } from '@/constants';
@@ -74,16 +76,25 @@ import * as testDb from '../shared/testDb';
import { v4 as uuid } from 'uuid';
import { handleLdapInit } from '@/Ldap/helpers';
import { ldapController } from '@/Ldap/routes/ldap.controller.ee';
import { InternalHooks } from '@/InternalHooks';
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
import { PostHogClient } from '@/posthog';
export const mockInstance = <T>(
ctor: new (...args: any[]) => T,
data: DeepPartial<T> | undefined = undefined,
) => {
const instance = mock<T>(data);
Container.set(ctor, instance);
return instance;
};
const loadNodesAndCredentials: INodesAndCredentials = {
loaded: { nodes: {}, credentials: {} },
known: { nodes: {}, credentials: {} },
credentialTypes: {} as ICredentialTypes,
};
const mockNodeTypes = NodeTypes(loadNodesAndCredentials);
CredentialTypes(loadNodesAndCredentials);
Container.set(LoadNodesAndCredentials, loadNodesAndCredentials);
/**
* Initialize a test server.
@@ -108,11 +119,9 @@ export async function initTestServer({
const logger = getLogger();
LoggerProxy.init(logger);
const postHog = new PostHogClient();
postHog.init('test-instance-id');
// Pre-requisite: Mock the telemetry module before calling.
await InternalHooksManager.init('test-instance-id', mockNodeTypes, postHog);
// Mock all telemetry.
mockInstance(InternalHooks);
mockInstance(PostHogClient);
testServer.app.use(bodyParser.json());
testServer.app.use(bodyParser.urlencoded({ extended: true }));
@@ -137,7 +146,7 @@ export async function initTestServer({
endpointGroups.includes('users') ||
endpointGroups.includes('passwordReset')
) {
testServer.externalHooks = ExternalHooks();
testServer.externalHooks = Container.get(ExternalHooks);
}
const [routerEndpoints, functionEndpoints] = classifyEndpointGroups(endpointGroups);
@@ -167,8 +176,8 @@ export async function initTestServer({
}
if (functionEndpoints.length) {
const externalHooks = ExternalHooks();
const internalHooks = InternalHooksManager.getInstance();
const externalHooks = Container.get(ExternalHooks);
const internalHooks = Container.get(InternalHooks);
const mailer = UserManagementMailer.getInstance();
const repositories = Db.collections;
@@ -218,7 +227,7 @@ export async function initTestServer({
externalHooks,
internalHooks,
repositories,
activeWorkflowRunner: ActiveWorkflowRunner.getInstance(),
activeWorkflowRunner: Container.get(ActiveWorkflowRunner),
logger,
}),
);
@@ -261,8 +270,8 @@ const classifyEndpointGroups = (endpointGroups: EndpointGroup[]) => {
/**
* Initialize node types.
*/
export async function initActiveWorkflowRunner(): Promise<ActiveWorkflowRunner.ActiveWorkflowRunner> {
const workflowRunner = ActiveWorkflowRunner.getInstance();
export async function initActiveWorkflowRunner(): Promise<ActiveWorkflowRunner> {
const workflowRunner = Container.get(ActiveWorkflowRunner);
workflowRunner.init();
return workflowRunner;
}
@@ -303,7 +312,7 @@ export function gitHubCredentialType(): ICredentialType {
* Initialize node types.
*/
export async function initCredentialsTypes(): Promise<void> {
loadNodesAndCredentials.loaded.credentials = {
Container.get(LoadNodesAndCredentials).loaded.credentials = {
githubApi: {
type: gitHubCredentialType(),
sourcePath: '',
@@ -322,7 +331,7 @@ export async function initLdapManager(): Promise<void> {
* Initialize node types.
*/
export async function initNodeTypes() {
loadNodesAndCredentials.loaded.nodes = {
Container.get(LoadNodesAndCredentials).loaded.nodes = {
'n8n-nodes-base.start': {
sourcePath: '',
type: {

View File

@@ -1,7 +1,13 @@
import { v4 as uuid } from 'uuid';
import { mocked } from 'jest-mock';
import { ICredentialTypes, LoggerProxy, NodeOperationError, Workflow } from 'n8n-workflow';
import {
ICredentialTypes,
INodesAndCredentials,
LoggerProxy,
NodeOperationError,
Workflow,
} from 'n8n-workflow';
import { ActiveWorkflowRunner } from '@/ActiveWorkflowRunner';
import * as Db from '@/Db';
@@ -10,12 +16,17 @@ import { SharedWorkflow } from '@/databases/entities/SharedWorkflow';
import { Role } from '@/databases/entities/Role';
import { User } from '@/databases/entities/User';
import { getLogger } from '@/Logger';
import { NodeTypes } from '@/NodeTypes';
import { CredentialTypes } from '@/CredentialTypes';
import { randomEmail, randomName } from '../integration/shared/random';
import * as Helpers from './Helpers';
import { WorkflowExecuteAdditionalData } from '@/index';
import { WorkflowRunner } from '@/WorkflowRunner';
import { mock } from 'jest-mock-extended';
import { ExternalHooks } from '@/ExternalHooks';
import { Container } from 'typedi';
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
import { mockInstance } from '../integration/shared/utils';
import { Push } from '@/push';
/**
* TODO:
@@ -112,19 +123,6 @@ jest.mock('@/Db', () => {
};
});
const mockExternalHooksRunFunction = jest.fn();
jest.mock('@/ExternalHooks', () => {
return {
ExternalHooks: () => {
return {
run: () => mockExternalHooksRunFunction(),
init: () => Promise.resolve(),
};
},
};
});
const workflowCheckIfCanBeActivated = jest.fn(() => true);
jest
@@ -140,30 +138,26 @@ const workflowExecuteAdditionalDataExecuteErrorWorkflowSpy = jest.spyOn(
);
describe('ActiveWorkflowRunner', () => {
let externalHooks: ExternalHooks;
let activeWorkflowRunner: ActiveWorkflowRunner;
beforeAll(async () => {
LoggerProxy.init(getLogger());
NodeTypes({
const nodesAndCredentials: INodesAndCredentials = {
loaded: {
nodes: MOCK_NODE_TYPES_DATA,
credentials: {},
},
known: { nodes: {}, credentials: {} },
credentialTypes: {} as ICredentialTypes,
});
CredentialTypes({
loaded: {
nodes: MOCK_NODE_TYPES_DATA,
credentials: {},
},
known: { nodes: {}, credentials: {} },
credentialTypes: {} as ICredentialTypes,
});
};
Container.set(LoadNodesAndCredentials, nodesAndCredentials);
mockInstance(Push);
});
beforeEach(() => {
activeWorkflowRunner = new ActiveWorkflowRunner();
externalHooks = mock();
activeWorkflowRunner = new ActiveWorkflowRunner(externalHooks);
});
afterEach(async () => {
@@ -173,84 +167,84 @@ describe('ActiveWorkflowRunner', () => {
});
test('Should initialize activeWorkflowRunner with empty list of active workflows and call External Hooks', async () => {
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(await activeWorkflowRunner.getActiveWorkflows()).toHaveLength(0);
expect(mocked(Db.collections.Workflow.find)).toHaveBeenCalled();
expect(mocked(Db.collections.Webhook.clear)).toHaveBeenCalled();
expect(mockExternalHooksRunFunction).toHaveBeenCalledTimes(1);
expect(externalHooks.run).toHaveBeenCalledTimes(1);
});
test('Should initialize activeWorkflowRunner with one active workflow', async () => {
databaseActiveWorkflowsCount = 1;
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(await activeWorkflowRunner.getActiveWorkflows()).toHaveLength(
databaseActiveWorkflowsCount,
);
expect(mocked(Db.collections.Workflow.find)).toHaveBeenCalled();
expect(mocked(Db.collections.Webhook.clear)).toHaveBeenCalled();
expect(mockExternalHooksRunFunction).toHaveBeenCalled();
expect(externalHooks.run).toHaveBeenCalled();
});
test('Should make sure function checkIfWorkflowCanBeActivated was called for every workflow', async () => {
databaseActiveWorkflowsCount = 2;
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(workflowCheckIfCanBeActivated).toHaveBeenCalledTimes(databaseActiveWorkflowsCount);
});
test('Call to removeAll should remove every workflow', async () => {
databaseActiveWorkflowsCount = 2;
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(await activeWorkflowRunner.getActiveWorkflows()).toHaveLength(
databaseActiveWorkflowsCount,
);
void (await activeWorkflowRunner.removeAll());
await activeWorkflowRunner.removeAll();
expect(removeFunction).toHaveBeenCalledTimes(databaseActiveWorkflowsCount);
});
test('Call to remove should also call removeWorkflowWebhooks', async () => {
databaseActiveWorkflowsCount = 1;
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(await activeWorkflowRunner.getActiveWorkflows()).toHaveLength(
databaseActiveWorkflowsCount,
);
void (await activeWorkflowRunner.remove('1'));
await activeWorkflowRunner.remove('1');
expect(removeWebhooksFunction).toHaveBeenCalledTimes(1);
});
test('Call to isActive should return true for valid workflow', async () => {
databaseActiveWorkflowsCount = 1;
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(await activeWorkflowRunner.isActive('1')).toBe(true);
});
test('Call to isActive should return false for invalid workflow', async () => {
databaseActiveWorkflowsCount = 1;
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
expect(await activeWorkflowRunner.isActive('2')).toBe(false);
});
test('Calling add should call checkIfWorkflowCanBeActivated', async () => {
// Initialize with default (0) workflows
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
generateWorkflows(1);
void (await activeWorkflowRunner.add('1', 'activate'));
await activeWorkflowRunner.add('1', 'activate');
expect(workflowCheckIfCanBeActivated).toHaveBeenCalledTimes(1);
});
test('runWorkflow should call run method in WorkflowRunner', async () => {
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
const workflow = generateWorkflows(1);
const additionalData = await WorkflowExecuteAdditionalData.getBase('fake-user-id');
workflowRunnerRun.mockImplementationOnce(() => Promise.resolve('invalid-execution-id'));
void (await activeWorkflowRunner.runWorkflow(
await activeWorkflowRunner.runWorkflow(
workflow[0],
workflow[0].nodes[0],
[[]],
additionalData,
'trigger',
));
);
expect(workflowRunnerRun).toHaveBeenCalledTimes(1);
});
@@ -258,7 +252,7 @@ describe('ActiveWorkflowRunner', () => {
test('executeErrorWorkflow should call function with same name in WorkflowExecuteAdditionalData', async () => {
const workflowData = generateWorkflows(1)[0];
const error = new NodeOperationError(workflowData.nodes[0], 'Fake error message');
void (await activeWorkflowRunner.init());
await activeWorkflowRunner.init();
activeWorkflowRunner.executeErrorWorkflow(error, workflowData, 'trigger');
expect(workflowExecuteAdditionalDataExecuteErrorWorkflowSpy).toHaveBeenCalledTimes(1);
});

View File

@@ -1,47 +1,47 @@
import type { ICredentialTypes, INodesAndCredentials } from 'n8n-workflow';
import { CredentialTypes } from '@/CredentialTypes';
import { Container } from 'typedi';
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
describe('ActiveExecutions', () => {
let credentialTypes: ICredentialTypes;
describe('CredentialTypes', () => {
const mockNodesAndCredentials: INodesAndCredentials = {
loaded: {
nodes: {},
credentials: {
fakeFirstCredential: {
type: {
name: 'fakeFirstCredential',
displayName: 'Fake First Credential',
properties: [],
},
sourcePath: '',
},
fakeSecondCredential: {
type: {
name: 'fakeSecondCredential',
displayName: 'Fake Second Credential',
properties: [],
},
sourcePath: '',
},
},
},
known: { nodes: {}, credentials: {} },
credentialTypes: {} as ICredentialTypes,
};
beforeEach(() => {
credentialTypes = CredentialTypes(mockNodesAndCredentials());
});
Container.set(LoadNodesAndCredentials, mockNodesAndCredentials);
const credentialTypes = Container.get(CredentialTypes);
test('Should throw error when calling invalid credential name', () => {
expect(() => credentialTypes.getByName('fakeThirdCredential')).toThrowError();
});
test('Should return correct credential type for valid name', () => {
const mockedCredentialTypes = mockNodesAndCredentials().loaded.credentials;
const mockedCredentialTypes = mockNodesAndCredentials.loaded.credentials;
expect(credentialTypes.getByName('fakeFirstCredential')).toStrictEqual(
mockedCredentialTypes.fakeFirstCredential.type,
);
});
});
const mockNodesAndCredentials = (): INodesAndCredentials => ({
loaded: {
nodes: {},
credentials: {
fakeFirstCredential: {
type: {
name: 'fakeFirstCredential',
displayName: 'Fake First Credential',
properties: [],
},
sourcePath: '',
},
fakeSecondCredential: {
type: {
name: 'fakeSecondCredential',
displayName: 'Fake Second Credential',
properties: [],
},
sourcePath: '',
},
},
},
known: { nodes: {}, credentials: {} },
credentialTypes: {} as ICredentialTypes,
});

View File

@@ -12,6 +12,9 @@ import {
import { CredentialsHelper } from '@/CredentialsHelper';
import { CredentialTypes } from '@/CredentialTypes';
import * as Helpers from './Helpers';
import { Container } from 'typedi';
import { NodeTypes } from '@/NodeTypes';
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
const TEST_ENCRYPTION_KEY = 'test';
const mockNodesAndCredentials: INodesAndCredentials = {
@@ -19,6 +22,7 @@ const mockNodesAndCredentials: INodesAndCredentials = {
known: { nodes: {}, credentials: {} },
credentialTypes: {} as ICredentialTypes,
};
Container.set(LoadNodesAndCredentials, mockNodesAndCredentials);
describe('CredentialsHelper', () => {
describe('authenticate', () => {
@@ -215,7 +219,7 @@ describe('CredentialsHelper', () => {
qs: {},
};
const nodeTypes = Helpers.NodeTypes();
const nodeTypes = Helpers.NodeTypes() as unknown as NodeTypes;
const workflow = new Workflow({
nodes: [node],
@@ -235,7 +239,7 @@ describe('CredentialsHelper', () => {
},
};
const credentialTypes = CredentialTypes(mockNodesAndCredentials);
const credentialTypes = Container.get(CredentialTypes);
const credentialsHelper = new CredentialsHelper(
TEST_ENCRYPTION_KEY,

View File

@@ -3,23 +3,13 @@ import { QueryFailedError } from 'typeorm';
import config from '@/config';
import { Db } from '@/index';
import { nodeFetchedData, workflowExecutionCompleted } from '@/events/WorkflowStatistics';
import { InternalHooksManager } from '@/InternalHooksManager';
import { getLogger } from '@/Logger';
import * as UserManagementHelper from '@/UserManagement/UserManagementHelper';
import * as UserManagementHelper from '@/UserManagement/UserManagementHelper';
import { InternalHooks } from '@/InternalHooks';
import { mockInstance } from '../integration/shared/utils';
const FAKE_USER_ID = 'abcde-fghij';
const mockedFirstProductionWorkflowSuccess = jest.fn((...args) => {});
const mockedFirstWorkflowDataLoad = jest.fn((...args) => {});
jest.spyOn(InternalHooksManager, 'getInstance').mockImplementation((...args) => {
const actual = jest.requireActual('@/InternalHooks');
return {
...actual,
onFirstProductionWorkflowSuccess: mockedFirstProductionWorkflowSuccess,
onFirstWorkflowDataLoad: mockedFirstWorkflowDataLoad,
};
});
jest.mock('@/Db', () => {
return {
collections: {
@@ -30,11 +20,13 @@ jest.mock('@/Db', () => {
},
};
});
jest.spyOn(UserManagementHelper, 'getWorkflowOwner').mockImplementation(async (workflowId) => {
jest.spyOn(UserManagementHelper, 'getWorkflowOwner').mockImplementation(async (_workflowId) => {
return { id: FAKE_USER_ID };
});
describe('Events', () => {
const internalHooks = mockInstance(InternalHooks);
beforeAll(() => {
config.set('diagnostics.enabled', true);
config.set('deployment.type', 'n8n-testing');
@@ -47,8 +39,8 @@ describe('Events', () => {
});
beforeEach(() => {
mockedFirstProductionWorkflowSuccess.mockClear();
mockedFirstWorkflowDataLoad.mockClear();
internalHooks.onFirstProductionWorkflowSuccess.mockClear();
internalHooks.onFirstWorkflowDataLoad.mockClear();
});
afterEach(() => {});
@@ -72,8 +64,8 @@ describe('Events', () => {
startedAt: new Date(),
};
await workflowExecutionCompleted(workflow, runData);
expect(mockedFirstProductionWorkflowSuccess).toBeCalledTimes(1);
expect(mockedFirstProductionWorkflowSuccess).toHaveBeenNthCalledWith(1, {
expect(internalHooks.onFirstProductionWorkflowSuccess).toBeCalledTimes(1);
expect(internalHooks.onFirstProductionWorkflowSuccess).toHaveBeenNthCalledWith(1, {
user_id: FAKE_USER_ID,
workflow_id: workflow.id,
});
@@ -97,12 +89,12 @@ describe('Events', () => {
startedAt: new Date(),
};
await workflowExecutionCompleted(workflow, runData);
expect(mockedFirstProductionWorkflowSuccess).toBeCalledTimes(0);
expect(internalHooks.onFirstProductionWorkflowSuccess).toBeCalledTimes(0);
});
test('should not send metrics for updated entries', async () => {
// Call the function with a fail insert, ensure update is called *and* metrics aren't sent
Db.collections.WorkflowStatistics.insert.mockImplementationOnce((...args) => {
Db.collections.WorkflowStatistics.insert.mockImplementationOnce(() => {
throw new QueryFailedError('invalid insert', [], '');
});
const workflow = {
@@ -121,7 +113,7 @@ describe('Events', () => {
startedAt: new Date(),
};
await workflowExecutionCompleted(workflow, runData);
expect(mockedFirstProductionWorkflowSuccess).toBeCalledTimes(0);
expect(internalHooks.onFirstProductionWorkflowSuccess).toBeCalledTimes(0);
});
});
@@ -138,8 +130,8 @@ describe('Events', () => {
parameters: {},
};
await nodeFetchedData(workflowId, node);
expect(mockedFirstWorkflowDataLoad).toBeCalledTimes(1);
expect(mockedFirstWorkflowDataLoad).toHaveBeenNthCalledWith(1, {
expect(internalHooks.onFirstWorkflowDataLoad).toBeCalledTimes(1);
expect(internalHooks.onFirstWorkflowDataLoad).toHaveBeenNthCalledWith(1, {
user_id: FAKE_USER_ID,
workflow_id: workflowId,
node_type: node.type,
@@ -165,8 +157,8 @@ describe('Events', () => {
},
};
await nodeFetchedData(workflowId, node);
expect(mockedFirstWorkflowDataLoad).toBeCalledTimes(1);
expect(mockedFirstWorkflowDataLoad).toHaveBeenNthCalledWith(1, {
expect(internalHooks.onFirstWorkflowDataLoad).toBeCalledTimes(1);
expect(internalHooks.onFirstWorkflowDataLoad).toHaveBeenNthCalledWith(1, {
user_id: FAKE_USER_ID,
workflow_id: workflowId,
node_type: node.type,
@@ -178,7 +170,7 @@ describe('Events', () => {
test('should not send metrics for entries that already have the flag set', async () => {
// Fetch data for workflow 2 which is set up to not be altered in the mocks
Db.collections.WorkflowStatistics.insert.mockImplementationOnce((...args) => {
Db.collections.WorkflowStatistics.insert.mockImplementationOnce(() => {
throw new QueryFailedError('invalid insert', [], '');
});
const workflowId = '1';
@@ -191,7 +183,7 @@ describe('Events', () => {
parameters: {},
};
await nodeFetchedData(workflowId, node);
expect(mockedFirstWorkflowDataLoad).toBeCalledTimes(0);
expect(internalHooks.onFirstWorkflowDataLoad).toBeCalledTimes(0);
});
});
});

View File

@@ -1,14 +1,13 @@
import { LoadNodesAndCredentials } from '@/LoadNodesAndCredentials';
import {
INodesAndCredentials,
INodeType,
INodeTypeData,
INodeTypes,
ITriggerFunctions,
ITriggerResponse,
IVersionedNodeType,
NodeHelpers,
} from 'n8n-workflow';
// TODO: delete this
class NodeTypesClass implements INodeTypes {
nodeTypes: INodeTypeData = {
'test.set': {
@@ -80,7 +79,7 @@ class NodeTypesClass implements INodeTypes {
},
};
constructor(nodesAndCredentials?: INodesAndCredentials) {
constructor(nodesAndCredentials?: LoadNodesAndCredentials) {
if (nodesAndCredentials?.loaded?.nodes) {
this.nodeTypes = nodesAndCredentials?.loaded?.nodes;
}
@@ -97,7 +96,7 @@ class NodeTypesClass implements INodeTypes {
let nodeTypesInstance: NodeTypesClass | undefined;
export function NodeTypes(nodesAndCredentials?: INodesAndCredentials): NodeTypesClass {
export function NodeTypes(nodesAndCredentials?: LoadNodesAndCredentials): NodeTypesClass {
if (nodeTypesInstance === undefined) {
nodeTypesInstance = new NodeTypesClass(nodesAndCredentials);
}

View File

@@ -45,7 +45,8 @@ describe('Telemetry', () => {
const postHog = new PostHogClient();
postHog.init(instanceId);
telemetry = new Telemetry(instanceId, postHog);
telemetry = new Telemetry(postHog);
telemetry.setInstanceId(instanceId);
(telemetry as any).rudderStack = {
flush: () => {},
identify: () => {},