// Copyright 2017-2019 @polkadot/api-derive 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 { ApiInterfaceRx } from '@polkadot/api/types'; import { AnyFunction } from '@polkadot/types/types'; import { Observable } from 'rxjs'; import * as accounts from './accounts'; import * as balances from './balances'; import * as chain from './chain'; import * as contracts from './contracts'; import * as democracy from './democracy'; import * as elections from './elections'; import * as imOnline from './imOnline'; import * as session from './session'; import * as staking from './staking'; export * from './type'; type DeriveSection
= { [Method in keyof Section]: Section[Method] extends AnyFunction ? ReturnType // ReturnType will be the inner function, i.e. without (api) argument : never; }; type DeriveAllSections = { [Section in keyof AllSections]: DeriveSection }; export type DeriveCustom = Record (...args: any[]) => Observable>>; /** * Returns an object that will inject `api` into all the functions inside * `allSections`, and keep the object architecture of `allSections`. */ function injectFunctions (api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections { return Object .keys(allSections) .reduce((deriveAcc, sectionName): DeriveAllSections => { const section = allSections[sectionName as keyof AllSections]; deriveAcc[sectionName as keyof AllSections] = Object .keys(section) .reduce((sectionAcc, _methodName): DeriveSection => { const methodName = _methodName as keyof typeof section; // Not sure what to do here, casting as any. Though the final types are good const method = (section[methodName] as any)(api); // idem (sectionAcc as any)[methodName] = method; return sectionAcc; }, {} as DeriveSection); return deriveAcc; }, {} as DeriveAllSections); } export const derive = { accounts, balances, chain, contracts, democracy, elections, imOnline, session, staking }; export type ExactDerive = DeriveAllSections; // FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom} // For now we just drop the custom derive typings export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive { return { ...injectFunctions(api, derive), ...injectFunctions(api, custom) }; }