Move indices cache to indices list (#2390)

This commit is contained in:
Jaco Greeff
2020-06-23 22:19:13 +02:00
committed by GitHub
parent a34a7450aa
commit bbbd82eb4a
2 changed files with 24 additions and 24 deletions
+7 -18
View File
@@ -5,14 +5,12 @@
import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
import { AccountIndexes } from '../types';
import { Observable, of } from 'rxjs';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
const cached = new Map<string, AccountIndex>();
/**
* @name idToIndex
* @param {( AccountId | string )} accountId - An accounts Id in different formats.
@@ -28,19 +26,10 @@ const cached = new Map<string, AccountIndex>();
* ```
*/
export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> => {
const address = accountId.toString();
if (cached.has(address)) {
return of(cached.get(address));
}
return api.derive.accounts.indexes().pipe(
map((indexes: AccountIndexes): AccountIndex | undefined => {
Object.entries(indexes).forEach(([address, index]) => cached.set(address, index));
return cached.get(address);
})
);
});
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> =>
api.derive.accounts.indexes().pipe(
map((indexes: AccountIndexes): AccountIndex | undefined =>
(indexes || {})[accountId.toString()]
)
));
}
+17 -6
View File
@@ -16,6 +16,8 @@ import { memo } from '../util';
const enumsetSize = ENUMSET_SIZE.toNumber();
let indicesCache: AccountIndexes | null = null;
function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
return api.query.indices.nextEnumSet<AccountIndex>().pipe(
// use the nextEnumSet (which is a counter of the number of sets) to construct
@@ -72,11 +74,20 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
*/
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo((): Observable<AccountIndexes> =>
(api.query.indices
? isFunction(api.query.indices.accounts)
? queryAccounts(api)
: queryEnumSet(api)
: of({} as AccountIndexes)
).pipe(startWith({}))
indicesCache
? of(indicesCache)
: (
api.query.indices
? isFunction(api.query.indices.accounts)
? queryAccounts(api).pipe(startWith({}))
: queryEnumSet(api).pipe(startWith({}))
: of({} as AccountIndexes)
).pipe(
map((indices): AccountIndexes => {
indicesCache = indices;
return indices;
})
)
);
}