Skip to content

Commit

Permalink
refactor: Async functions don't need to explicitly return promises (n…
Browse files Browse the repository at this point in the history
…o-changelog) (#6041)
  • Loading branch information
netroy authored Apr 24, 2023
1 parent 03be725 commit 308a943
Show file tree
Hide file tree
Showing 31 changed files with 149 additions and 210 deletions.
4 changes: 2 additions & 2 deletions packages/cli/src/CredentialsHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,10 +542,10 @@ export class CredentialsHelper extends ICredentialsHelper {
): Promise<INodeCredentialTestResult> {
const credentialTestFunction = this.getCredentialTestFunction(credentialType);
if (credentialTestFunction === undefined) {
return Promise.resolve({
return {
status: 'Error',
message: 'No testing function found for this credential.',
});
};
}

if (credentialsDecrypted.data) {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/InternalHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,12 +271,12 @@ export class InternalHooks implements IInternalHooksClass {
runData?: IRun,
userId?: string,
): Promise<void> {
const promises = [Promise.resolve()];

if (!workflow.id) {
return Promise.resolve();
return;
}

const promises = [];

const properties: IExecutionTrackProperties = {
workflow_id: workflow.id,
is_manual: false,
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/Ldap/LdapService.ee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class LdapService {
await this.client.unbind();
return searchEntries;
}
return Promise.resolve([]);
return [];
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/posthog/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class PostHogClient {
}

async getFeatureFlags(user: Pick<PublicUser, 'id' | 'createdAt'>): Promise<FeatureFlags> {
if (!this.postHog) return Promise.resolve({});
if (!this.postHog) return {};

const fullId = [this.instanceId, user.id].join('#');

Expand Down
3 changes: 1 addition & 2 deletions packages/cli/src/sso/saml/saml.service.ee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,8 @@ export class SamlService {
validate: async (response: string) => {
const valid = await validateResponse(response);
if (!valid) {
return Promise.reject(new Error('Invalid SAML response'));
throw new Error('Invalid SAML response');
}
return Promise.resolve();
},
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/telemetry/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export class Telemetry {

private async pulse(): Promise<unknown> {
if (!this.rudderStack) {
return Promise.resolve();
return;
}

const allPromises = Object.keys(this.executionCountsBuffer).map(async (workflowId) => {
Expand Down
28 changes: 7 additions & 21 deletions packages/cli/test/integration/ldap/ldap.api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,7 @@ test('GET /ldap/config route should retrieve current configuration', async () =>

describe('POST /ldap/test-connection', () => {
test('route should success', async () => {
jest
.spyOn(LdapService.prototype, 'testConnection')
.mockImplementation(async () => Promise.resolve());
jest.spyOn(LdapService.prototype, 'testConnection').mockResolvedValue();

const response = await authAgent(owner).post('/ldap/test-connection');
expect(response.statusCode).toBe(200);
Expand All @@ -216,9 +214,7 @@ describe('POST /ldap/test-connection', () => {
test('route should fail', async () => {
const errorMessage = 'Invalid connection';

jest
.spyOn(LdapService.prototype, 'testConnection')
.mockImplementation(async () => Promise.reject(new Error(errorMessage)));
jest.spyOn(LdapService.prototype, 'testConnection').mockRejectedValue(new Error(errorMessage));

const response = await authAgent(owner).post('/ldap/test-connection');
expect(response.statusCode).toBe(400);
Expand All @@ -240,9 +236,7 @@ describe('POST /ldap/sync', () => {

describe('dry mode', () => {
const runTest = async (ldapUsers: LdapUser[]) => {
jest
.spyOn(LdapService.prototype, 'searchWithAdminBinding')
.mockImplementation(async () => Promise.resolve(ldapUsers));
jest.spyOn(LdapService.prototype, 'searchWithAdminBinding').mockResolvedValue(ldapUsers);

const response = await authAgent(owner).post('/ldap/sync').send({ type: 'dry' });

Expand Down Expand Up @@ -337,9 +331,7 @@ describe('POST /ldap/sync', () => {

describe('live mode', () => {
const runTest = async (ldapUsers: LdapUser[]) => {
jest
.spyOn(LdapService.prototype, 'searchWithAdminBinding')
.mockImplementation(async () => Promise.resolve(ldapUsers));
jest.spyOn(LdapService.prototype, 'searchWithAdminBinding').mockResolvedValue(ldapUsers);

const response = await authAgent(owner).post('/ldap/sync').send({ type: 'live' });

Expand Down Expand Up @@ -467,9 +459,7 @@ describe('POST /ldap/sync', () => {
test('should remove user instance access once the user is disabled during synchronization', async () => {
const member = await testDb.createLdapUser({ globalRole: globalMemberRole }, uniqueId());

jest
.spyOn(LdapService.prototype, 'searchWithAdminBinding')
.mockImplementation(async () => Promise.resolve([]));
jest.spyOn(LdapService.prototype, 'searchWithAdminBinding').mockResolvedValue([]);

await authAgent(owner).post('/ldap/sync').send({ type: 'live' });

Expand Down Expand Up @@ -508,13 +498,9 @@ describe('POST /login', () => {

const authlessAgent = utils.createAgent(app);

jest
.spyOn(LdapService.prototype, 'searchWithAdminBinding')
.mockImplementation(async () => Promise.resolve([ldapUser]));
jest.spyOn(LdapService.prototype, 'searchWithAdminBinding').mockResolvedValue([ldapUser]);

jest
.spyOn(LdapService.prototype, 'validUser')
.mockImplementation(async () => Promise.resolve());
jest.spyOn(LdapService.prototype, 'validUser').mockResolvedValue();

const response = await authlessAgent
.post('/login')
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/integration/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -799,11 +799,11 @@ export function installedNodePayload(packageName: string): InstalledNodePayload
};
}

export const emptyPackage = () => {
export const emptyPackage = async () => {
const installedPackage = new InstalledPackages();
installedPackage.installedNodes = [];

return Promise.resolve(installedPackage);
return installedPackage;
};

// ----------------------------------
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/test/unit/ActiveExecutions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jest.mock('@/Db', () => {
return {
collections: {
Execution: {
save: jest.fn(async () => Promise.resolve({ id: FAKE_EXECUTION_ID })),
save: jest.fn(async () => ({ id: FAKE_EXECUTION_ID })),
update: jest.fn(),
},
},
Expand Down
9 changes: 4 additions & 5 deletions packages/cli/test/unit/ActiveWorkflowRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,20 +99,19 @@ jest.mock('@/Db', () => {
return {
collections: {
Workflow: {
find: jest.fn(async () => Promise.resolve(generateWorkflows(databaseActiveWorkflowsCount))),
find: jest.fn(async () => generateWorkflows(databaseActiveWorkflowsCount)),
findOne: jest.fn(async (searchParams) => {
const foundWorkflow = databaseActiveWorkflowsList.find(
return databaseActiveWorkflowsList.find(
(workflow) => workflow.id.toString() === searchParams.where.id.toString(),
);
return Promise.resolve(foundWorkflow);
}),
update: jest.fn(),
createQueryBuilder: jest.fn(() => {
const fakeQueryBuilder = {
update: () => fakeQueryBuilder,
set: () => fakeQueryBuilder,
where: () => fakeQueryBuilder,
execute: () => Promise.resolve(),
execute: async () => {},
};
return fakeQueryBuilder;
}),
Expand Down Expand Up @@ -246,7 +245,7 @@ describe('ActiveWorkflowRunner', () => {
const workflow = generateWorkflows(1);
const additionalData = await WorkflowExecuteAdditionalData.getBase('fake-user-id');

workflowRunnerRun.mockImplementationOnce(() => Promise.resolve('invalid-execution-id'));
workflowRunnerRun.mockResolvedValueOnce('invalid-execution-id');

await activeWorkflowRunner.runWorkflow(
workflow[0],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jest.mock('@/Db', () => {
return {
collections: {
ExecutionMetadata: {
save: jest.fn(async () => Promise.resolve([])),
save: jest.fn(async () => []),
},
},
};
Expand Down
98 changes: 45 additions & 53 deletions packages/core/src/BinaryDataManager/FileSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,84 +134,76 @@ export class BinaryDataFileSystem implements IBinaryDataManager {

const execsAdded: { [key: string]: number } = {};

const proms = metaFileNames.reduce(
(prev, curr) => {
const [prefix, executionId, ts] = curr.split('_');
const promises = metaFileNames.reduce<Array<Promise<void>>>((prev, curr) => {
const [prefix, executionId, ts] = curr.split('_');

if (prefix !== filePrefix) {
if (prefix !== filePrefix) {
return prev;
}

const execTimestamp = parseInt(ts, 10);

if (execTimestamp < currentTimeValue) {
if (execsAdded[executionId]) {
// do not delete data, only meta file
prev.push(this.deleteMetaFileByPath(path.join(metaPath, curr)));
return prev;
}

const execTimestamp = parseInt(ts, 10);

if (execTimestamp < currentTimeValue) {
if (execsAdded[executionId]) {
// do not delete data, only meta file
prev.push(this.deleteMetaFileByPath(path.join(metaPath, curr)));
return prev;
}

execsAdded[executionId] = 1;
prev.push(
this.deleteBinaryDataByExecutionId(executionId).then(async () =>
this.deleteMetaFileByPath(path.join(metaPath, curr)),
),
);
}
execsAdded[executionId] = 1;
prev.push(
this.deleteBinaryDataByExecutionId(executionId).then(async () =>
this.deleteMetaFileByPath(path.join(metaPath, curr)),
),
);
}

return prev;
},
[Promise.resolve()],
);
return prev;
}, []);

return Promise.all(proms).then(() => {});
await Promise.all(promises);
}

async duplicateBinaryDataByIdentifier(binaryDataId: string, prefix: string): Promise<string> {
const newBinaryDataId = this.generateFileName(prefix);

return fs
.copyFile(this.resolveStoragePath(binaryDataId), this.resolveStoragePath(newBinaryDataId))
.then(() => newBinaryDataId);
await fs.copyFile(
this.resolveStoragePath(binaryDataId),
this.resolveStoragePath(newBinaryDataId),
);
return newBinaryDataId;
}

async deleteBinaryDataByExecutionId(executionId: string): Promise<void> {
const regex = new RegExp(`${executionId}_*`);
const filenames = await fs.readdir(this.storagePath);

const proms = filenames.reduce(
(allProms, filename) => {
if (regex.test(filename)) {
allProms.push(fs.rm(this.resolveStoragePath(filename)));
}

return allProms;
},
[Promise.resolve()],
);
const promises = filenames.reduce<Array<Promise<void>>>((allProms, filename) => {
if (regex.test(filename)) {
allProms.push(fs.rm(this.resolveStoragePath(filename)));
}
return allProms;
}, []);

return Promise.all(proms).then(async () => Promise.resolve());
await Promise.all(promises);
}

async deleteBinaryDataByIdentifier(identifier: string): Promise<void> {
return this.deleteFromLocalStorage(identifier);
}

async persistBinaryDataForExecutionId(executionId: string): Promise<void> {
return fs.readdir(this.getBinaryDataPersistMetaPath()).then(async (metafiles) => {
const proms = metafiles.reduce(
(prev, curr) => {
if (curr.startsWith(`${PREFIX_PERSISTED_METAFILE}_${executionId}_`)) {
prev.push(fs.rm(path.join(this.getBinaryDataPersistMetaPath(), curr)));
return prev;
}

return fs.readdir(this.getBinaryDataPersistMetaPath()).then(async (metaFiles) => {
const promises = metaFiles.reduce<Array<Promise<void>>>((prev, curr) => {
if (curr.startsWith(`${PREFIX_PERSISTED_METAFILE}_${executionId}_`)) {
prev.push(fs.rm(path.join(this.getBinaryDataPersistMetaPath(), curr)));
return prev;
},
[Promise.resolve()],
);
}

return prev;
}, []);

return Promise.all(proms).then(() => {});
await Promise.all(promises);
});
}

Expand All @@ -227,8 +219,8 @@ export class BinaryDataFileSystem implements IBinaryDataManager {
return path.join(this.storagePath, 'persistMeta');
}

private async deleteMetaFileByPath(metafilePath: string): Promise<void> {
return fs.rm(metafilePath);
private async deleteMetaFileByPath(metaFilePath: string): Promise<void> {
return fs.rm(metaFilePath);
}

private async deleteFromLocalStorage(identifier: string) {
Expand Down
20 changes: 6 additions & 14 deletions packages/core/src/BinaryDataManager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,38 +158,30 @@ export class BinaryDataManager {

async markDataForDeletionByExecutionId(executionId: string): Promise<void> {
if (this.managers[this.binaryDataMode]) {
return this.managers[this.binaryDataMode].markDataForDeletionByExecutionId(executionId);
await this.managers[this.binaryDataMode].markDataForDeletionByExecutionId(executionId);
}

return Promise.resolve();
}

async markDataForDeletionByExecutionIds(executionIds: string[]): Promise<void> {
if (this.managers[this.binaryDataMode]) {
return Promise.all(
await Promise.all(
executionIds.map(async (id) =>
this.managers[this.binaryDataMode].markDataForDeletionByExecutionId(id),
),
).then(() => {});
);
}

return Promise.resolve();
}

async persistBinaryDataForExecutionId(executionId: string): Promise<void> {
if (this.managers[this.binaryDataMode]) {
return this.managers[this.binaryDataMode].persistBinaryDataForExecutionId(executionId);
await this.managers[this.binaryDataMode].persistBinaryDataForExecutionId(executionId);
}

return Promise.resolve();
}

async deleteBinaryDataByExecutionId(executionId: string): Promise<void> {
if (this.managers[this.binaryDataMode]) {
return this.managers[this.binaryDataMode].deleteBinaryDataByExecutionId(executionId);
await this.managers[this.binaryDataMode].deleteBinaryDataByExecutionId(executionId);
}

return Promise.resolve();
}

async duplicateBinaryData(
Expand Down Expand Up @@ -218,7 +210,7 @@ export class BinaryDataManager {
return Promise.all(returnInputData);
}

return Promise.resolve(inputData as INodeExecutionData[][]);
return inputData as INodeExecutionData[][];
}

private generateBinaryId(filename: string) {
Expand Down
Loading

0 comments on commit 308a943

Please sign in to comment.