Skip to content

Commit

Permalink
chore(core): enable eslint and remove tslint (#12982)
Browse files Browse the repository at this point in the history
* chore(core): enable eslint and remove tslint

* chore(core): run yarn lint:fix

* chore(core): manual fix of errors reported by yarn lint

* chore(notifications): fix the type issue raised after linting core

* chore(storage): rename imports from core package
  • Loading branch information
HuiSF authored Feb 13, 2024
1 parent e316a2e commit b96a0ed
Show file tree
Hide file tree
Showing 140 changed files with 754 additions and 645 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ module.exports = {
'api-graphql',
'auth',
'aws-amplify',
'core',
// 'core',
'datastore',
'datastore-storage-adapter',
'geo',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import { HttpResponse, MiddlewareHandler } from '../../../../src/clients/types';
import { composeTransferHandler } from '../../../../src/clients/internal/composeTransferHandler';
import {
retryMiddleware,
retryMiddlewareFactory,
RetryOptions,
} from '../../../../src/clients/middleware/retry';

jest.spyOn(global, 'setTimeout');
jest.spyOn(global, 'clearTimeout');

describe(`${retryMiddleware.name} middleware`, () => {
describe(`${retryMiddlewareFactory.name} middleware`, () => {
beforeEach(() => {
jest.clearAllMocks();
});
Expand All @@ -27,7 +27,7 @@ describe(`${retryMiddleware.name} middleware`, () => {
headers: {},
};
const getRetryableHandler = (nextHandler: MiddlewareHandler<any, any>) =>
composeTransferHandler<[RetryOptions]>(nextHandler, [retryMiddleware]);
composeTransferHandler<[RetryOptions]>(nextHandler, [retryMiddlewareFactory]);

test('should retry specified times', async () => {
const nextHandler = jest.fn().mockResolvedValue(defaultResponse);
Expand Down Expand Up @@ -189,7 +189,7 @@ describe(`${retryMiddleware.name} middleware`, () => {

const doubleRetryableHandler = composeTransferHandler<
[RetryOptions, {}, RetryOptions]
>(coreHandler, [retryMiddleware, betweenRetryMiddleware, retryMiddleware]);
>(coreHandler, [retryMiddlewareFactory, betweenRetryMiddleware, retryMiddlewareFactory]);

const retryDecider = jest
.fn()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { composeTransferHandler } from '../../../../src/clients/internal/composeTransferHandler';
import {
signingMiddleware,
signingMiddlewareFactory,
SigningOptions,
} from '../../../../src/clients/middleware/signing';
import { getSkewCorrectedDate } from '../../../../src/clients/middleware/signing/utils/getSkewCorrectedDate';
Expand Down Expand Up @@ -50,7 +50,7 @@ describe('Signing middleware', () => {
const getSignableHandler = (nextHandler: MiddlewareHandler<any, any>) =>
composeTransferHandler<[SigningOptions], HttpRequest, HttpResponse>(
nextHandler,
[signingMiddleware]
[signingMiddlewareFactory]
);
beforeEach(() => {
jest.clearAllMocks();
Expand Down Expand Up @@ -125,7 +125,7 @@ describe('Signing middleware', () => {
},
});

const middlewareFunction = signingMiddleware(defaultSigningOptions)(
const middlewareFunction = signingMiddlewareFactory(defaultSigningOptions)(
nextHandler
);

Expand Down
3 changes: 2 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"clean": "npm run clean:size && rimraf dist lib lib-esm",
"clean:size": "rimraf dual-publish-tmp tmp*",
"format": "echo \"Not implemented\"",
"lint": "tslint 'src/**/*.ts' && npm run ts-coverage",
"lint": "eslint '**/*.{ts,tsx}' && npm run ts-coverage",
"lint:fix": "eslint '**/*.{ts,tsx}' --fix",
"prepublishOnly": "npm run build",
"ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 92.36"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,6 @@ export class BackgroundProcessManager {
*/
private jobs = new Set<JobEntry>();

/**
* Creates a new manager for promises, observables, and other types
* of work that may be running in the background. This manager provides
* a centralized mechanism to request termination and await completion.
*/
constructor() {}

/**
* Executes an async `job` function, passing the return value through to
* the caller, registering it as a running job in the manager. When the
Expand All @@ -61,7 +54,7 @@ export class BackgroundProcessManager {
*/
add<T>(
job: (onTerminate: Promise<void>) => Promise<T>,
description?: string
description?: string,
): Promise<T>;

/**
Expand All @@ -76,8 +69,8 @@ export class BackgroundProcessManager {
* @returns Job promise hooks + onTerminate signaling promise
*/
add(description?: string): {
resolve: (value?: unknown) => void;
reject: (reason?: any) => void;
resolve(value?: unknown): void;
reject(reason?: any): void;
onTerminate: Promise<void>;
};

Expand All @@ -96,7 +89,7 @@ export class BackgroundProcessManager {
| string
| BackgroundProcessManager
| ((...args: any) => Promise<T>),
optionalDescription?: string
optionalDescription?: string,
) {
let job:
| BackgroundProcessManager
Expand All @@ -120,10 +113,10 @@ export class BackgroundProcessManager {
} else if (typeof job === 'function') {
return this.addFunction(job, description);
} else if (job instanceof BackgroundProcessManager) {
return this.addManager(job, description);
this.addManager(job, description);
} else {
throw new Error(
'If `job` is provided, it must be an Observable, Function, or BackgroundProcessManager.'
'If `job` is provided, it must be an Observable, Function, or BackgroundProcessManager.',
);
}
}
Expand All @@ -140,7 +133,7 @@ export class BackgroundProcessManager {
*/
addCleaner<T>(
clean: () => Promise<T>,
description?: string
description?: string,
): () => Promise<void> {
const { resolve, onTerminate } = this.addHook(description);

Expand All @@ -156,15 +149,17 @@ export class BackgroundProcessManager {

private addFunction<T>(
job: () => Promise<T>,
description?: string
description?: string,
): Promise<T>;

private addFunction<T>(
job: (onTerminate: Promise<void>) => Promise<T>,
description?: string
description?: string,
): Promise<T>;

private addFunction<T>(
job: (() => Promise<T>) | ((onTerminate: Promise<void>) => Promise<T>),
description?: string
description?: string,
) {
// the function we call when we want to try to terminate this job.
let terminate;
Expand All @@ -183,7 +178,7 @@ export class BackgroundProcessManager {
this.registerPromise(
jobResult,
terminate as unknown as () => void,
description
description,
);
}

Expand All @@ -194,7 +189,7 @@ export class BackgroundProcessManager {
}

private addManager(manager: BackgroundProcessManager, description?: string) {
this.addCleaner(async () => await manager.close(), description);
this.addCleaner(async () => manager.close(), description);
}

/**
Expand All @@ -210,33 +205,33 @@ export class BackgroundProcessManager {
private addHook(description?: string) {
// the resolve/reject functions we'll provide to the caller to signal
// the state of the job.
let resolve!: (value?: unknown) => void;
let reject!: (reason?: any) => void;
let promiseResolve!: (value?: unknown) => void;
let promiseReject!: (reason?: any) => void;

// the underlying promise we'll use to manage it, pretty much like
// any other promise.
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
const promise = new Promise((resolve, reject) => {
promiseResolve = resolve;
promiseReject = reject;
});

// the function we call when we want to try to terminate this job.
let terminate;

// the promise the job can opt into listening to for termination.
const onTerminate = new Promise(resolveTerminate => {
terminate = resolveTerminate;
const onTerminate = new Promise(resolve => {
terminate = resolve;
});

this.registerPromise(
promise,
terminate as unknown as () => void,
description
description,
);

return {
resolve,
reject,
resolve: promiseResolve,
reject: promiseReject,
onTerminate,
};
}
Expand All @@ -255,7 +250,7 @@ export class BackgroundProcessManager {
private registerPromise<T extends Promise<any>>(
promise: T,
terminate: () => void,
description?: string
description?: string,
) {
const jobEntry = { promise, terminate, description };
this.jobs.add(jobEntry);
Expand Down Expand Up @@ -345,8 +340,8 @@ export class BackgroundProcessManager {
`Pending jobs: [\n${this.pending
.map(t => ' ' + t)
.join(',\n')}\n]`,
].join('\n')
)
].join('\n'),
),
);
}
}
Expand Down Expand Up @@ -382,15 +377,15 @@ export class BackgroundProcessManager {
`Failed to send termination signal to job. Error: ${
(error as Error).message
}`,
job
job,
);
}
}

// Use `allSettled()` because we want to wait for all to finish. We do
// not want to stop waiting if there is a failure.
this._closingPromise = Promise.allSettled(
Array.from(this.jobs).map(j => j.promise)
Array.from(this.jobs).map(j => j.promise),
);

await this._closingPromise;
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/BackgroundProcessManager/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export enum BackgroundProcessManagerState {
* Completely internal to `BackgroundProcessManager`, and describes the structure of
* an entry in the jobs registry.
*/
export type JobEntry = {
export interface JobEntry {
/**
* The underlying promise provided by the job function to wait for.
*/
Expand All @@ -34,7 +34,7 @@ export type JobEntry = {
/**
* Request the termination of the job.
*/
terminate: () => void;
terminate(): void;

/**
* An object provided by the caller that can be used to identify the description
Expand All @@ -46,4 +46,4 @@ export type JobEntry = {
* on `close()`.
*/
description?: string;
};
}
5 changes: 5 additions & 0 deletions packages/core/src/Cache/StorageCache.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// SPDX-License-Identifier: Apache-2.0

import { loadAsyncStorage } from '@aws-amplify/react-native';

import { ConsoleLogger } from '../Logger';

import { defaultConfig } from './constants';
import { StorageCacheCommon } from './StorageCacheCommon';
import { Cache, CacheConfig } from './types';
Expand Down Expand Up @@ -38,6 +40,7 @@ export class StorageCache extends StorageCacheCommon implements Cache {
keys.push(key.substring(this.config.keyPrefix.length));
}
}

return keys;
}

Expand All @@ -46,6 +49,7 @@ export class StorageCache extends StorageCacheCommon implements Cache {
return AsyncStorage.getAllKeys();
} catch (e) {
logger.warn(`getAllKeys failed! ${e}`);

return [];
}
}
Expand All @@ -60,6 +64,7 @@ export class StorageCache extends StorageCacheCommon implements Cache {
logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');
config.keyPrefix = getCurrentTime.toString();
}

return new StorageCache(config);
}
}
2 changes: 2 additions & 0 deletions packages/core/src/Cache/StorageCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { ConsoleLogger } from '../Logger';
import { KeyValueStorage } from '../storage/KeyValueStorage';
import { getLocalStorageWithFallback } from '../storage/utils';

import { defaultConfig } from './constants';
import { StorageCacheCommon } from './StorageCacheCommon';
import { Cache, CacheConfig } from './types';
Expand Down Expand Up @@ -42,6 +43,7 @@ export class StorageCache extends StorageCacheCommon implements Cache {
keys.push(key.substring(this.config.keyPrefix.length));
}
}

return keys;
}

Expand Down
Loading

0 comments on commit b96a0ed

Please sign in to comment.