@cosmology/ast
Version:
Cosmos TypeScript AST generation
64 lines (63 loc) • 2.73 kB
JavaScript
import * as ast from "@babel/types";
/**
*
* @param context
* @param service
* @param methodKey e.g. "balance"
* @param helperCreatorName e.g. "createGetBalance"
* @returns
*/
export function createMsgHelperCreator(context, service, helperCreatorName) {
context.addUtil("buildTx");
context.addUtil("ISigningClient");
context.addUtil("buildUseMutation");
context.addUtil("SigningClientResolver");
context.addUtil("toEncoders");
context.addUtil("toConverters");
const callExpression = ast.callExpression(ast.identifier("buildTx"), [
ast.objectExpression([
ast.objectProperty(ast.identifier("clientResolver"), ast.identifier("clientResolver"), false, true),
ast.objectProperty(ast.identifier("typeUrl"), ast.memberExpression(ast.identifier(service.requestType), ast.identifier("typeUrl"))),
ast.objectProperty(ast.identifier("encoders"), ast.callExpression(ast.identifier("toEncoders"), [
ast.identifier(service.requestType),
])),
ast.objectProperty(ast.identifier("converters"), ast.callExpression(ast.identifier("toConverters"), [
ast.identifier(service.requestType),
])),
]),
]);
callExpression.typeParameters = ast.tsTypeParameterInstantiation([
ast.tsTypeReference(ast.identifier(service.requestType)),
]);
const customHookArgumentsType = ast.tsTypeAnnotation(ast.tsTypeReference(ast.identifier("SigningClientResolver")));
const arg = ast.identifier("clientResolver");
arg.typeAnnotation = customHookArgumentsType;
arg.optional = true;
const arrowFuncExp = ast.arrowFunctionExpression([arg], callExpression);
return ast.exportNamedDeclaration(ast.variableDeclaration("const", [
ast.variableDeclarator(ast.identifier(helperCreatorName), arrowFuncExp),
]));
}
/**
*
* @param context
* @param service
* @param methodKey e.g. "balance"
* @param helperCreatorName e.g. "createGetBalance"
* @param hookName e.g. "useGetBalance"
* @returns
*/
export function createMsgHooks(context, service, helperCreatorName, hookName) {
const callExpression = ast.callExpression(ast.identifier("buildUseMutation"), [
ast.objectExpression([
ast.objectProperty(ast.identifier("builderMutationFn"), ast.identifier(helperCreatorName)),
]),
]);
callExpression.typeParameters = ast.tsTypeParameterInstantiation([
ast.tsTypeReference(ast.identifier(service.requestType)),
ast.tsTypeReference(ast.identifier(`Error`)),
]);
return ast.exportNamedDeclaration(ast.variableDeclaration("const", [
ast.variableDeclarator(ast.identifier(hookName), callExpression),
]));
}