fetch metadata via websocket in polkadot-types-from-defs (#4773)

* add ability to fetch metadata from websocket connection as stated in usage https://github.com/polkadot-js/api/blob/master/packages/typegen/src/fromDefs.ts\#L20

* exit after websocket

Co-authored-by: Alex D <pr0fedt@gmail.com>
This commit is contained in:
Alex D
2022-04-26 20:13:29 +03:00
committed by GitHub
co-authored by Alex D
parent b2e71be983
commit 5c2bd9dfa7
+36 -7
View File
@@ -7,6 +7,7 @@ import path from 'path';
import yargs from 'yargs';
import * as substrateDefs from '@polkadot/types/interfaces/definitions';
import { WebSocket } from '@polkadot/x-ws';
import { generateInterfaceTypes } from './generate/interfaceRegistry';
import { generateTsDef } from './generate/tsDef';
@@ -32,13 +33,6 @@ export function main (): void {
}
}).argv as ArgV;
if (endpoint) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const metaHex = (require(path.join(process.cwd(), endpoint)) as Record<string, HexString>).result;
generateDefaultLookup(path.join(process.cwd(), input), metaHex);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')) as Record<string, any>;
const userKeys = Object.keys(userDefs);
@@ -66,4 +60,39 @@ export function main (): void {
generateTsDef(allDefs, path.join(process.cwd(), input), pkg);
generateInterfaceTypes(allDefs, path.join(process.cwd(), input, 'augment-types.ts'));
if (endpoint) {
if (endpoint.startsWith('wss://') || endpoint.startsWith('ws://')) {
try {
const websocket = new WebSocket(endpoint);
websocket.onclose = (event: { code: number; reason: string }): void => {
console.error(`disconnected, code: '${event.code}' reason: '${event.reason}'`);
process.exit(1);
};
websocket.onerror = (event: unknown): void => {
console.error(event);
process.exit(1);
};
websocket.onopen = (): void => {
console.log('connected');
websocket.send('{"id":"1","jsonrpc":"2.0","method":"state_getMetadata","params":[]}');
};
websocket.onmessage = (message: unknown): void => {
generateDefaultLookup(path.join(process.cwd(), input), (JSON.parse((message as Record<string, string>).data) as Record<string, HexString>).result);
process.exit(0);
};
} catch (error) {
process.exit(1);
}
} else {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const metaHex = (require(path.join(process.cwd(), endpoint)) as Record<string, HexString>).result;
generateDefaultLookup(path.join(process.cwd(), input), metaHex);
}
}
}