Skip to content

Commit

Permalink
fix(eslint): enable @typescript-eslint/require-await (NangoHQ#2381)
Browse files Browse the repository at this point in the history
## Describe your changes

- enable `@typescript-eslint/require-await` and fix all related errors
  • Loading branch information
bodinsamuel authored Jun 21, 2024
1 parent 44cb094 commit 0187f22
Show file tree
Hide file tree
Showing 39 changed files with 113 additions and 105 deletions.
20 changes: 12 additions & 8 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@
"node": true
},
"plugins": [
"@typescript-eslint",
"react",
"react-hooks"
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
Expand All @@ -25,10 +23,7 @@
"plugin:@typescript-eslint/strict",
"plugin:@typescript-eslint/strict-type-checked",
"plugin:@typescript-eslint/stylistic",
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:prettier/recommended",
"plugin:react-hooks/recommended",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/recommended"
Expand All @@ -37,11 +32,11 @@
"no-console": "warn",
"prettier/prettier": "error",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/require-await": "error",
// Previously warn but now errors
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-explicit-any": "warn",
// To reenable as error progressively
"@typescript-eslint/require-await": "warn",
"@typescript-eslint/no-floating-promises": "warn",
"@typescript-eslint/no-unsafe-assignment": "warn",
"@typescript-eslint/no-unsafe-member-access": "warn",
Expand All @@ -65,7 +60,6 @@
"@typescript-eslint/consistent-type-exports": "error",
"@typescript-eslint/no-unnecessary-condition": "off", // Our types are not good enough right now
"@typescript-eslint/only-throw-error": "warn",
"react/prop-types": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
Expand Down Expand Up @@ -161,6 +155,15 @@
"files": [
"packages/webapp/**/*.tsx"
],
"plugins": [
"react",
"react-hooks"
],
"extends": [
"plugin:react-hooks/recommended",
"plugin:react/recommended",
"plugin:react/jsx-runtime",
],
"env": {
"browser": true,
"es6": true,
Expand All @@ -177,6 +180,7 @@
},
"rules": {
"no-console": "off",
"react/prop-types": "off",
"@typescript-eslint/no-misused-promises": [
"warn",
{
Expand Down
4 changes: 2 additions & 2 deletions integration-templates/notion/syncs/rich-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ const blockToMarkdown = async (nango: NangoSync, block: any) => {
image_title = matches ? matches[0] : image_title;
}

return await image(image_title, link);
return image(image_title, link);
}
case 'divider': {
return divider();
Expand Down Expand Up @@ -534,7 +534,7 @@ const todo = (text: string, checked: boolean) => {
return checked ? `- [x] ${text}` : `- [ ] ${text}`;
};

const image = async (alt: string, href: string): Promise<string> => {
const image = (alt: string, href: string): string => {
if (href.startsWith('data:')) {
const base64 = href.split(',').pop();
return `![${alt}](data:image/png;base64,${base64})`;
Expand Down
34 changes: 14 additions & 20 deletions packages/cli/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ program
program
.command('init')
.description('Initialize a new Nango project')
.action(async function (this: Command) {
.action(function (this: Command) {
const { debug } = this.opts();
const fullPath = process.cwd();
init({ absolutePath: fullPath, debug });
Expand All @@ -97,7 +97,7 @@ program
program
.command('generate')
.description('Generate a new Nango integration')
.action(async function (this: Command) {
.action(function (this: Command) {
const { debug } = this.opts();
generate({ fullPath: process.cwd(), debug });
});
Expand Down Expand Up @@ -155,19 +155,17 @@ program
.option('-a, --action [actionName]', 'Optional deploy only this action name.')
.option('--no-compile-interfaces', `Don't compile the ${nangoConfigFile}`, true)
.action(async function (this: Command, environment: string) {
const options = this.opts();
(async (options: DeployOptions) => {
const { debug } = options;
const fullPath = process.cwd();
await deployService.prep({ fullPath, options: { ...options, env: 'production' as ENV }, environment, debug });
})(options as DeployOptions);
const options: DeployOptions = this.opts();
const { debug } = options;
const fullPath = process.cwd();
await deployService.prep({ fullPath, options: { ...options, env: 'production' as ENV }, environment, debug });
});

program
.command('migrate-config')
.description('Migrate the nango.yaml from v1 (deprecated) to v2')
.action(async function (this: Command) {
await v1toV2Migration(path.resolve(process.cwd(), NANGO_INTEGRATIONS_LOCATION));
.action(function (this: Command) {
v1toV2Migration(path.resolve(process.cwd(), NANGO_INTEGRATIONS_LOCATION));
});

program
Expand All @@ -188,11 +186,9 @@ program
.option('-v, --version [version]', 'Optional: Set a version of this deployment to tag this integration with. Can be used for rollbacks.')
.option('--no-compile-interfaces', `Don't compile the ${nangoConfigFile}`, true)
.action(async function (this: Command, environment: string) {
const options = this.opts();
(async (options: DeployOptions) => {
const fullPath = process.cwd();
await deployService.prep({ fullPath, options: { ...options, env: 'local' }, environment, debug: options.debug });
})(options as DeployOptions);
const options: DeployOptions = this.opts();
const fullPath = process.cwd();
await deployService.prep({ fullPath, options: { ...options, env: 'local' }, environment, debug: options.debug });
});

program
Expand All @@ -210,11 +206,9 @@ program
.option('-v, --version [version]', 'Optional: Set a version of this deployment to tag this integration with. Can be used for rollbacks.')
.option('--no-compile-interfaces', `Don't compile the ${nangoConfigFile}`, true)
.action(async function (this: Command, environment: string) {
const options = this.opts();
(async (options: DeployOptions) => {
const fullPath = process.cwd();
await deployService.prep({ fullPath, options: { ...options, env: 'staging' }, environment, debug: options.debug });
})(options as DeployOptions);
const options: DeployOptions = this.opts();
const fullPath = process.cwd();
await deployService.prep({ fullPath, options: { ...options, env: 'staging' }, environment, debug: options.debug });
});

program
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/lib/services/local-integration.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Buffer } from 'buffer';

class IntegrationService implements IntegrationServiceInterface {
async cancelScript() {
return;
return Promise.resolve();
}

async runScript({ syncName, nangoProps, isInvokedImmediately, isWebhook, optionalLoadLocation, input }: RunScriptOptions): Promise<RunnerOutput> {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/lib/services/migration.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { nangoConfigFile } from '@nangohq/nango-yaml';
import { printDebug, getNangoRootPath } from '../utils.js';
import { load } from './config.service.js';

export const v1toV2Migration = async (loadLocation: string): Promise<void> => {
export const v1toV2Migration = (loadLocation: string): void => {
if (process.env['NANGO_CLI_UPGRADE_MODE'] === 'ignore') {
return;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/lib/sync.unit.cli-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('generate function tests', () => {
consoleMock.mockReset();
});

it('should init the expected files in the nango-integrations directory', async () => {
it('should init the expected files in the nango-integrations directory', () => {
const dir = getTestDirectory('init');
init({ absolutePath: path.resolve(dir, '..'), debug: false });
expect(fs.existsSync(`${dir}/demo-github-integration/syncs/${exampleSyncName}.ts`)).toBe(true);
Expand Down
2 changes: 1 addition & 1 deletion packages/database/lib/db.integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, describe, it } from 'vitest';
import { multipleMigrations } from './index.js';

describe('Migration test', async () => {
describe('Migration test', () => {
it('Should run migrations successfully', async () => {
await multipleMigrations();

Expand Down
2 changes: 1 addition & 1 deletion packages/jobs/lib/crons/autoIdleDemo.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { exec } from './autoIdleDemo.js';
import { nanoid, Ok } from '@nangohq/utils';

describe('Auto Idle Demo', async () => {
describe('Auto Idle Demo', () => {
let env: Environment;
beforeAll(async () => {
await multipleMigrations();
Expand Down
2 changes: 1 addition & 1 deletion packages/jobs/lib/processor/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,5 +299,5 @@ async function webhook(task: TaskWebhook): Promise<Result<JsonValue>> {
}

async function postConnection(task: TaskPostConnection): Promise<Result<JsonValue>> {
return Err(`Not implemented: ${JSON.stringify({ taskId: task.id })}`);
return Promise.resolve(Err(`Not implemented: ${JSON.stringify({ taskId: task.id })}`));
}
6 changes: 3 additions & 3 deletions packages/jobs/lib/processor/processor.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ export class ProcessorChild {
}
this.opts = workerData;
this.parent = parent;
this.parent.on('message', async (msg: 'start' | 'stop') => {
this.parent.on('message', (msg: 'start' | 'stop') => {
switch (msg) {
case 'start':
await this.start();
this.start();
break;
case 'stop':
this.stop();
Expand All @@ -83,7 +83,7 @@ export class ProcessorChild {
});
}

async start(): Promise<void> {
start(): void {
logger.info(`Starting Processor: ${JSON.stringify(this.opts)}`);
this.processor.start({ tracer });
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jobs/lib/runner/local.runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class LocalRunner implements Runner {
});
}

return new LocalRunner(runnerId, `http://localhost:${port}`, childProcess);
return Promise.resolve(new LocalRunner(runnerId, `http://localhost:${port}`, childProcess));
} catch (err) {
throw new Error(`Unable to get runner ${runnerId}: ${err}`);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jobs/lib/runner/remote.runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ export class RemoteRunner implements Runner {
}

static async getOrStart(runnerId: string): Promise<RemoteRunner> {
return new RemoteRunner(runnerId, process.env['RUNNER_SERVICE_URL'] || 'http://nango-runner');
return Promise.resolve(new RemoteRunner(runnerId, process.env['RUNNER_SERVICE_URL'] || 'http://nango-runner'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const scheduler = new Scheduler({
const port = await getPort();
const orchestratorClient = new OrchestratorClient({ baseUrl: `http://localhost:${port}` });

describe('OrchestratorProcessor', async () => {
describe('OrchestratorProcessor', () => {
const server = getServer(scheduler, eventsHandler);

beforeAll(async () => {
Expand All @@ -42,7 +42,7 @@ describe('OrchestratorProcessor', async () => {

it('should process tasks and mark them as successful if processing succeed', async () => {
const groupKey = nanoid();
const mockProcess = vi.fn(async (): Promise<Result<JsonValue>> => Ok({ foo: 'bar' }));
const mockProcess = vi.fn(async (): Promise<Result<JsonValue>> => Promise.resolve(Ok({ foo: 'bar' })));
const n = 10;
await processN(mockProcess, groupKey, n);

Expand All @@ -54,7 +54,7 @@ describe('OrchestratorProcessor', async () => {
});
it('should process tasks and mark them as failed if processing failed', async () => {
const groupKey = nanoid();
const mockProcess = vi.fn(async (): Promise<Result<JsonValue>> => Err('Failed'));
const mockProcess = vi.fn(async (): Promise<Result<JsonValue>> => Promise.resolve(Err('Failed')));
const n = 10;
await processN(mockProcess, groupKey, n);

Expand Down
2 changes: 1 addition & 1 deletion packages/orchestrator/lib/routes/v1/postDequeue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const handler = (scheduler: Scheduler, eventEmitter: EventEmitter) => {
respond(res);
}
};
const onTaskStarted = async (_t: Task) => {
const onTaskStarted = (_t: Task) => {
cleanupAndRespond(async (res) => {
const getTasks = await scheduler.dequeue({ groupKey, limit });
if (getTasks.isErr()) {
Expand Down
4 changes: 2 additions & 2 deletions packages/server/lib/clients/publisher.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const enum MessageType {

export type WebSocketClientId = string;

class Redis {
export class Redis {
// Two redis clients are needed because the same client cannot be used for both publishing and subscribing
// more at https://redis.io/commands/subscribe/
private url: string;
Expand Down Expand Up @@ -52,7 +52,7 @@ class Redis {
}

public async subscribe(channel: string, onMessage: (message: string, channel: string) => void) {
await this.sub.subscribe(channel, async (message, channel) => {
await this.sub.subscribe(channel, (message, channel) => {
onMessage(message, channel);
});
}
Expand Down
21 changes: 12 additions & 9 deletions packages/server/lib/clients/publisher.client.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/unbound-method */
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { WebSocketClientId } from './publisher.client';
import { Publisher } from './publisher.client';
import { Redis, Publisher } from './publisher.client';
import type { WebSocket } from 'ws';
import * as uuid from 'uuid';

Expand All @@ -19,29 +19,32 @@ const mockRes = ({ status }: { status: number }) => {
return mock;
};

class MockRedis {
class MockRedis extends Redis {
// Caveat: only one subscription per channel is supported
private subscriptions = new Map<string, (message: string, channel: string) => void>();
constructor() {
super('');
}

public async publish(channel: string, message: string) {
public override async publish(channel: string, message: string) {
const onMessage = this.subscriptions.get(channel);
if (onMessage) {
onMessage(message, channel);
}
return true;
return Promise.resolve();
}

public async subscribe(channel: string, onMessage: (message: string, channel: string) => void) {
public override async subscribe(channel: string, onMessage: (message: string, channel: string) => void) {
this.subscriptions.set(channel, onMessage);
return true;
return Promise.resolve();
}

public async unsubscribe(channel: string) {
public override async unsubscribe(channel: string) {
this.subscriptions.delete(channel);
return true;
return Promise.resolve();
}
}
const mockRedis = new MockRedis() as any;
const mockRedis = new MockRedis();

describe('Publisher', () => {
let publisher1: Publisher;
Expand Down
6 changes: 3 additions & 3 deletions packages/server/lib/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const createAccountIfNotInvited = async (name: string, state?: string): Promise<
};

class AuthController {
async logout(req: Request, res: Response<any, never>, next: NextFunction) {
logout(req: Request, res: Response<any, never>, next: NextFunction) {
try {
req.session.destroy((err) => {
if (err) {
Expand Down Expand Up @@ -105,7 +105,7 @@ class AuthController {
}
}

async resetPassword(req: Request, res: Response<any, never>, next: NextFunction) {
resetPassword(req: Request, res: Response<any, never>, next: NextFunction) {
try {
const { password, token } = req.body;

Expand Down Expand Up @@ -142,7 +142,7 @@ class AuthController {
}
}

async sendResetPasswordEmail(user: User, token: string) {
sendResetPasswordEmail(user: User, token: string) {
try {
const emailClient = EmailClient.getInstance();
emailClient
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const locals: Required<RequestLocals> = {
* UPDATE: ✅
* DELETE: ✅
*/
describe('Should verify the config controller HTTP API calls', async () => {
describe('Should verify the config controller HTTP API calls', () => {
beforeAll(async () => {
await multipleMigrations();

Expand Down
2 changes: 1 addition & 1 deletion packages/server/lib/controllers/config.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ class ConfigController {
}
}

async listProvidersFromYaml(_: Request, res: Response<any, Required<RequestLocals>>, next: NextFunction) {
listProvidersFromYaml(_: Request, res: Response<any, Required<RequestLocals>>, next: NextFunction) {
try {
const providers = Object.entries(configService.getTemplates())
.map((providerProperties: [string, ProviderTemplate]) => {
Expand Down
Loading

0 comments on commit 0187f22

Please sign in to comment.