fix: don't format "unorthodox" query input types (#1934)

* fix: don't format "unorthodox" query input types

Also add support for tuples in `getSimilarTypes`

* fix: refactor type ignore logic into `formatType`

Had to use a regexp solution because types like `([AccountId | string | Uint8Array, Data | { none: any } | { raw: any } | { blakeTwo256: any } | { sha256: any } | { keccak256: any } | { shaThree256: any } | string | Uint8Array])[]` were not being ignored with the current logic, so they were passed to `getTypeDef` and causing delimiter errors.

* refactor: remove superfluous "FirstKeyType" param
This commit is contained in:
Jeremías Díaz
2020-02-24 22:31:18 +01:00
committed by GitHub
parent d85d9ca930
commit c6355fb147
8 changed files with 49 additions and 31 deletions
+2 -2
View File
@@ -61,7 +61,7 @@ function onSocketOpen (): boolean {
export default function main (): void {
const { endpoint, output, package: pkg, strict: isStrict } = yargs.strict().options({
endpoint: {
description: 'The endpoint to connect to, e.g. wss://kusama-rpc.polkadot.io or relative file to JSON output',
description: 'The endpoint to connect to (e.g. wss://kusama-rpc.polkadot.io) or relative path to a file containing the JSON output of an RPC state_getMetadata call',
type: 'string',
required: true
},
@@ -75,7 +75,7 @@ export default function main (): void {
type: 'string'
},
strict: {
description: 'Turns on stict mode, no output of catch-all generic versions',
description: 'Turns on strict mode, no output of catch-all generic versions',
type: 'boolean'
}
}).argv;
+6 -7
View File
@@ -26,6 +26,8 @@ function addModifier (storageEntry: StorageEntryMetadataLatest, returnType: stri
// From a storage entry metadata, we return [args, returnType]
/** @internal */
function entrySignature (allDefs: object, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
const format = (type: string): string => formatType(allDefs, type, imports);
if (storageEntry.type.isPlain) {
setImports(allDefs, imports, [storageEntry.type.asPlain.toString()]);
@@ -40,7 +42,7 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor
]);
return [
`arg: ${similarTypes.map((type) => formatType(allDefs, type, imports)).join(' | ')}`,
`arg: ${similarTypes.map(format).join(' | ')}`,
formatType(allDefs, addModifier(storageEntry, storageEntry.type.asMap.value.toString()), imports)
];
} else if (storageEntry.type.isDoubleMap) {
@@ -54,8 +56,8 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor
storageEntry.type.asDoubleMap.value.toString()
]);
const key1Types = similarTypes1.map((type) => formatType(allDefs, type, imports)).join(' | ');
const key2Types = similarTypes2.map((type) => formatType(allDefs, type, imports)).join(' | ');
const key1Types = similarTypes1.map(format).join(' | ');
const key2Types = similarTypes2.map(format).join(' | ');
return [
`key1: ${key1Types}, key2: ${key2Types}`,
@@ -78,16 +80,13 @@ function generateModule (allDefs: object, registry: Registry, { name, storage }:
.concat(storage.unwrap().items.map((storageEntry): string => {
const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports);
let entryType = 'AugmentedQuery';
const entryTypeArgs: string[] = ['ApiType', `(${args}) => Observable<${returnType}>`];
if (storageEntry.type.isDoubleMap) {
entryType = `${entryType}DoubleMap`;
const firstKeyTypes = /^key1: (.*), key2/.exec(args)![1];
entryTypeArgs.push(firstKeyTypes);
}
return createDocComments(6, storageEntry.documentation) +
indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: ${entryType}<${entryTypeArgs.join(', ')}> & QueryableStorageEntry<ApiType>;`);
indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: ${entryType}<ApiType, (${args}) => Observable<${returnType}>> & QueryableStorageEntry<ApiType>;`);
}))
.concat([indent(4)('};')]);
}
+1 -5
View File
@@ -43,11 +43,7 @@ function generateModule (registry: Registry, allDefs: object, { calls, name }: M
const params = args
.map(({ name, type }): [string, string, string] => {
const typeStr = type.toString();
const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string =>
type.startsWith('(') || type.startsWith('{')
? type
: formatType(allDefs, type, imports)
);
const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string => formatType(allDefs, type, imports));
const nameStr = mapName(name);
setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]);
+11
View File
@@ -13,6 +13,7 @@ import Option from '@polkadot/types/codec/Option';
import Struct from '@polkadot/types/codec/Struct';
import UInt from '@polkadot/types/codec/UInt';
import Vec from '@polkadot/types/codec/Vec';
import Tuple from '@polkadot/types/codec/Tuple';
import GenericAccountId from '@polkadot/types/generic/AccountId';
import GenericAddress from '@polkadot/types/generic/Address';
import Vote, { convictionNames as _voteConvictions } from '@polkadot/types/generic/Vote';
@@ -80,6 +81,8 @@ export function getSimilarTypes (definitions: object, registry: Registry, _type:
} else if (type === 'StorageKey') {
// TODO We can do better
return ['StorageKey', 'string', 'Uint8Array', 'any'];
} else if (type === '()') {
return ['null'];
}
const Clazz = ClassOfUnsafe(registry, type);
@@ -133,6 +136,14 @@ export function getSimilarTypes (definitions: object, registry: Registry, _type:
possibleTypes.push('string', 'Uint8Array');
} else if (isChildClass(String, Clazz)) {
possibleTypes.push('string');
} else if (isChildClass(Tuple, Clazz)) {
const subDef = getTypeDef(type).sub;
if (Array.isArray(subDef)) {
const subs = subDef.map(({ type }) => getSimilarTypes(definitions, registry, type, imports).join(' | '));
possibleTypes.push(`[${subs.join(', ')}]`);
}
}
return possibleTypes;
+6
View File
@@ -137,6 +137,12 @@ export function formatType (definitions: object, type: string | TypeDef, imports
let typeDef: TypeDef;
if (typeof type === 'string') {
// If type is "unorthodox" (i.e. `{ something: any }` for an Enum input or `[a | b | c, d | e | f]` for a Tuple's similar types),
// we return it as-is
if (/(^{.+:.+})|^\([^,]+\)|^\(.+\)\[\]|^\[([^;]+|)?[^;]+\]/.exec(type)) {
return type;
}
typeDef = getTypeDef(type);
} else {
typeDef = type;
+8 -2
View File
@@ -50,9 +50,10 @@ export function setImports (allDefs: object, imports: TypeImports, types: string
genericTypes[type] = true;
} else if ((primitiveClasses as any)[type] || type === 'Metadata') {
primitiveTypes[type] = true;
} else if (type.includes('<') || type.includes('(') || type.includes('[')) {
} else if (type.includes('<') || type.includes('(') || (type.includes('[') && !type.includes('|'))) {
// If the type is a bit special (tuple, fixed u8, nested type...), then we
// need to parse it with `getTypeDef`.
// need to parse it with `getTypeDef`. We skip the case where type ~ [a | b | c ... , ... , ... w | y | z ]
// since that represents a tuple's similar types, which are covered in the next block
const typeDef = getTypeDef(type);
setImports(allDefs, imports, [TypeDefInfo[typeDef.info]]);
@@ -64,6 +65,11 @@ export function setImports (allDefs: object, imports: TypeImports, types: string
// typeDef.sub is a TypeDef in this case
setImports(allDefs, imports, [typeDef.sub.type]);
}
} else if (type.includes('[') && type.includes('|')) {
// We split the types
const splitTypes = /\[\s?(.+?)\s?\]/.exec(type)![1].split(/\s?\|\s?/);
setImports(allDefs, imports, splitTypes);
} else {
// find this module inside the exports from the rest
const [moduleName] = Object.entries(allDefs).find(([, { types }]): boolean =>