eslint rules (#1099)

* Off to the races - 3760 problems (1794 errors, 1966 warnings)

* Convert Array<T> -> T[] (not all correct, eg. extends)

* () => { -> (): void  => {

* get is/as -> public get is/as

* public for getters, constructors & base Codec

* Some cleanups from previous overzealous search & replace

* Under 2k, 1874 problems (649 errors, 1225 warnings)

* ^^^ check that commit for details ;)

* Minor.

* rm config header

* Minor cleanups

* Default to tslint, eslint as option

* Trigger

* Update jsonrpc

* 1494 problems (433 errors, 1061 warnings)

* 1103 problems (135 errors, 968 warnings)

* 899 problems (9 errors, 890 warnings)

* 483 problems (9 errors, 474 warnings) (ignore any... for now)

* 366 problems (9 errors, 357 warnings)

* 336 problems (9 errors, 327 warnings)

* 148 problems (9 errors, 139 warnings)

* 31 problems (8 errors, 23 warnings)

* 0, 0
This commit is contained in:
Jaco Greeff
2019-07-14 12:15:14 +02:00
committed by GitHub
parent f770fb973f
commit 71c5920b1f
354 changed files with 3817 additions and 3632 deletions
+44 -38
View File
@@ -1,9 +1,10 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ProviderInterface, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
import { MockState$Subscriptions, MockState$Subscription$Callback, MockState$Db } from './types';
import { ProviderInterface, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
import { MockStateSubscriptions, MockStateSubscriptionCallback, MockStateDb } from './types';
import BN from 'bn.js';
import EventEmitter from 'eventemitter3';
@@ -18,13 +19,13 @@ import { randomAsU8a } from '@polkadot/util-crypto';
const INTERVAL = 1000;
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
[], Object.values(interfaces).map((area) =>
[], Object.values(interfaces).map((area): string[] =>
Object
.values(area.methods)
.filter((method) =>
.filter((method): boolean =>
method.isSubscription
)
.map(({ method, section }) =>
.map(({ method, section }): string =>
`${section}_${method}`
)
)
@@ -38,60 +39,65 @@ const l = logger('api-mock');
* @return {ProviderInterface} The mock provider
*/
export default class Mock implements ProviderInterface {
private db: MockState$Db = {};
private db: MockStateDb = {};
private emitter = new EventEmitter();
public isUpdating: boolean = true;
private requests: { [index: string]: (...params: any[]) => string } = {
'chain_getBlockHash': (blockNumber: number): string => '0x1234',
'chain_getRuntimeVersion': (): string => new RuntimeVersion().toHex(),
'state_getStorage': (storage: MockState$Db, params: Array<any>): string => {
private requests: Record<string, (...params: any[]) => string> = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
chain_getBlockHash: (blockNumber: number): string => '0x1234',
chain_getRuntimeVersion: (): string => new RuntimeVersion().toHex(),
state_getStorage: (storage: MockStateDb, params: any[]): string => {
return u8aToHex(
storage[(params[0] as string)]
);
},
'system_chain': (): string => 'mockChain',
'state_getMetadata': (): string => rpcMetadataV6,
'system_name': (): string => 'mockClient',
'system_version': (): string => '9.8.7'
system_chain: (): string => 'mockChain',
state_getMetadata: (): string => rpcMetadataV6,
system_name: (): string => 'mockClient',
system_version: (): string => '9.8.7'
};
public subscriptions: MockState$Subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
public subscriptions: MockStateSubscriptions = SUBSCRIPTIONS.reduce((subs, name): MockStateSubscriptions => {
subs[name] = {
callbacks: {},
lastValue: null
};
return subs;
}, ({} as MockState$Subscriptions));
private subscriptionId: number = 0;
private subscriptionMap: {
[index: number]: string
} = {};
}, ({} as unknown as MockStateSubscriptions));
constructor () {
private subscriptionId: number = 0;
private subscriptionMap: Record<number, string> = {};
public constructor () {
this.init();
}
get hasSubscriptions (): boolean {
public get hasSubscriptions (): boolean {
return true;
}
clone (): Mock {
public clone (): Mock {
throw new Error('Unimplemented');
}
disconnect (): void {
public disconnect (): void {
// noop
}
isConnected (): boolean {
public isConnected (): boolean {
return true;
}
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): void {
this.emitter.on(type, sub);
}
async send (method: string, params: Array<any>): Promise<any> {
public async send (method: string, params: any[]): Promise<any> {
if (!this.requests[method]) {
throw new Error(`provider.send: Invalid method '${method}'`);
}
@@ -99,11 +105,11 @@ export default class Mock implements ProviderInterface {
return this.requests[method](this.db, params);
}
async subscribe (type: string, method: string, ...params: Array<any>): Promise<number> {
l.debug(() => ['subscribe', method, params]);
public async subscribe (type: string, method: string, ...params: any[]): Promise<number> {
l.debug((): any => ['subscribe', method, params]);
if (this.subscriptions[method]) {
const callback: MockState$Subscription$Callback = params.pop();
const callback: MockStateSubscriptionCallback = params.pop();
const id = ++this.subscriptionId;
this.subscriptions[method].callbacks[id] = callback;
@@ -119,10 +125,10 @@ export default class Mock implements ProviderInterface {
throw new Error(`provider.subscribe: Invalid method '${method}'`);
}
async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
const sub = this.subscriptionMap[id];
l.debug(() => ['unsubscribe', id, sub]);
l.debug((): any => ['unsubscribe', id, sub]);
if (!sub) {
throw new Error(`Unable to find subscription for ${id}`);
@@ -134,14 +140,14 @@ export default class Mock implements ProviderInterface {
return true;
}
private init () {
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
private init (): void {
const emitEvents: ProviderInterfaceEmitted[] = ['connected', 'disconnected'];
let emitIndex = 0;
let newHead = this.makeBlockHeader(new BN(-1));
let counter = -1;
// Do something every 1 seconds
setInterval(() => {
setInterval((): void => {
if (!this.isUpdating) {
return;
}
@@ -150,7 +156,7 @@ export default class Mock implements ProviderInterface {
newHead = this.makeBlockHeader(newHead.blockNumber.toBn());
// increment the balances and nonce for each account
keyring.getPairs().forEach(({ publicKey }, index) => {
keyring.getPairs().forEach(({ publicKey }, index): void => {
this.setStateBn(storage.balances.freeBalance(publicKey), newHead.blockNumber.muln(3).iaddn(index));
this.setStateBn(storage.system.accountNonce(publicKey), newHead.blockNumber.addn(index));
});
@@ -190,12 +196,12 @@ export default class Mock implements ProviderInterface {
this.db[u8aToHex(key)] = bnToU8a(value, 64, true);
}
private updateSubs (method: string, value: Codec) {
private updateSubs (method: string, value: Codec): void {
this.subscriptions[method].lastValue = value;
Object
.values(this.subscriptions[method].callbacks)
.forEach((cb) => {
.forEach((cb): void => {
try {
cb(null, value.toJSON());
} catch (error) {
+8 -8
View File
@@ -2,24 +2,24 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ProviderInterface$Emitted } from '../types';
import { ProviderInterfaceEmitted } from '../types';
import Mock from './';
describe('on', () => {
describe('on', (): void => {
let mock: Mock;
beforeEach(() => {
beforeEach((): void => {
mock = new Mock();
});
it('it emits both connected and disconnected events', (done) => {
const events: { [index: string]: boolean } = { connected: false, disconnected: false };
const handler = (type: ProviderInterface$Emitted) => {
mock.on(type, () => {
it('it emits both connected and disconnected events', (done): void => {
const events: Record<string, boolean> = { connected: false, disconnected: false };
const handler = (type: ProviderInterfaceEmitted): void => {
mock.on(type, (): void => {
events[type] = true;
if (Object.values(events).filter((value) => value).length === 2) {
if (Object.values(events).filter((value): boolean => value).length === 2) {
done();
}
});
+6 -6
View File
@@ -4,25 +4,25 @@
import Mock from './';
describe('send', () => {
describe('send', (): void => {
let mock: Mock;
beforeEach(() => {
beforeEach((): void => {
mock = new Mock();
});
it('fails on non-supported methods', () => {
it('fails on non-supported methods', (): Promise<any> => {
return mock
.send('something_invalid', [])
.catch((error) => {
.catch((error): void => {
expect(error.message).toMatch(/Invalid method/);
});
});
it('returns values for mocked requests', () => {
it('returns values for mocked requests', (): Promise<void> => {
return mock
.send('system_name', [])
.then((result) => {
.then((result): void => {
expect(result).toBe('mockClient');
});
});
@@ -4,51 +4,51 @@
import Mock from './';
describe('subscribe', () => {
describe('subscribe', (): void => {
let mock: Mock;
beforeEach(() => {
beforeEach((): void => {
mock = new Mock();
});
it('fails on unknown methods', () => {
it('fails on unknown methods', (): Promise<number | void> => {
return mock
.subscribe('test', 'test_notFound')
.catch((error) => {
.catch((error): void => {
expect(error.message).toMatch(/Invalid method 'test_notFound'/);
});
});
it('returns a subscription id', () => {
it('returns a subscription id', (): Promise<void> => {
return mock
.subscribe('chain_newHead', 'chain_subscribeNewHead', () => void 0)
.then((id) => {
.subscribe('chain_newHead', 'chain_subscribeNewHead', (): void => void 0)
.then((id): void => {
expect(id).toEqual(1);
});
});
it('calls back with the last known value', (done) => {
it('calls back with the last known value', (done): Promise<number> => {
mock.isUpdating = false;
mock.subscriptions['chain_subscribeNewHead'].lastValue = 'testValue';
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, value: string) => {
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, value: string): void => {
expect(value).toEqual('testValue');
done();
});
});
it('calls back with new headers', (done) => {
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any) => {
it('calls back with new headers', (done): Promise<number> => {
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => {
if (header.number === 4) {
done();
}
});
});
it('handles errors withing callbacks gracefully', (done) => {
let hasThrown: boolean = false;
it('handles errors withing callbacks gracefully', (done): Promise<number> => {
let hasThrown = false;
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any) => {
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => {
if (!hasThrown) {
hasThrown = true;
+13 -21
View File
@@ -10,28 +10,20 @@ export interface Global extends NodeJS.Global {
fetch: GlobalFetch;
}
export type Mock = {
body: Object,
requests: Number,
server: Server
done: () => {}
};
export interface Mock {
body: Record<string, any>;
requests: number;
server: Server;
done: () => {};
}
export type MockState$Subscription$Callback = (error: Error | null, value: any) => void;
export type MockStateSubscriptionCallback = (error: Error | null, value: any) => void;
export type MockState$Subscriptions = {
[index: string]: {
callbacks: {
[index: number]: MockState$Subscription$Callback
},
lastValue: any
}
};
export type MockStateSubscriptions = Record<string, {
callbacks: Record<number, MockStateSubscriptionCallback>;
lastValue: any;
}>;
export type MockState$Db = {
[index: string]: Uint8Array
};
export type MockStateDb = Record<string, Uint8Array>;
export type MockState$Requests = {
[index: string]: (db: MockState$Db, params: Array<any>) => string
};
export type MockStateRequests = Record<string, (db: MockStateDb, params: any[]) => string>;
@@ -4,37 +4,43 @@
import Mock from './';
describe('unsubscribe', () => {
describe('unsubscribe', (): void => {
let mock: Mock;
let id: number;
beforeEach(() => {
beforeEach((): Promise<void> => {
mock = new Mock();
return mock
.subscribe('chain_newHead', 'chain_subscribeNewHead', () => void 0)
.then((_id) => {
.subscribe('chain_newHead', 'chain_subscribeNewHead', (): void => void 0)
.then((_id): void => {
id = _id;
});
});
it('fails on unknown ids', () => {
it('fails on unknown ids', (): Promise<boolean> => {
return mock
.unsubscribe('chain_newHead', 'chain_subscribeNewHead', 5)
.catch((error) => {
.catch((error): boolean => {
expect(error.message).toMatch(/Unable to find/);
return false;
});
});
it('unsubscribes successfully', () => {
it('unsubscribes successfully', (): Promise<boolean> => {
return mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id);
});
it('fails on double unsubscribe', () => {
it('fails on double unsubscribe', (): Promise<boolean> => {
return mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id)
.then(() => mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id))
.catch((error) => {
.then((): Promise<boolean> =>
mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id)
)
.catch((error): boolean => {
expect(error.message).toMatch(/Unable to find/);
return false;
});
});
});