import { BaseVisitor, Context } from "@apexlang/core/model"; import { isService, pascalCase } from "../utils"; import { translations } from "./constant"; import { PathDirective } from "../rest"; import { expandType, parseNamespaceName } from "./helpers"; export class MinimalAPIVisitor extends BaseVisitor { visitNamespaceBefore(context: Context) { this.write(`// Code generated by @apexlang/codegen. DO NOT EDIT.\n\n`); this.write(`using System;\nusing Microsoft.AspNetCore.Builder;\n\n`); super.visitNamespaceBefore(context); } visitNamespace(context: Context) { this.write(`namespace ${parseNamespaceName(context.namespace.name)} {\n`); super.visitNamespace(context); } visitNamespaceAfter(context: Context) { this.write(`}\n`); super.visitNamespaceAfter(context); } visitInterfaceBefore(context: Context): void { if (!isService(context)) { return; } const { interface: iface } = context; const visitor = new ApiServiceVisitor(this.writer); iface.accept(context, visitor); } } export class ApiServiceVisitor extends BaseVisitor { visitInterfaceBefore(context: Context): void { let path = ""; context.namespace.annotation("path", (a) => { path = a?.convert().value; }); this.write(` public class Setup {\n`); this.write( ` public Setup(WebApplication app, ${pascalCase( context.interface.name )} service) {\n` ); for (const method of context.interface.operations) { let subPath = ""; method.annotation("path", (a) => { subPath = a?.convert().value; }); this.write(` app.`); if (method.annotation("GET")) { this.write(`MapGet`); } else if (method.annotation("POST")) { this.write(`MapPost`); } else if (method.annotation("PUT")) { this.write(`MapPut`); } else if (method.annotation("DELETE")) { this.write(`MapDelete`); } this.write(`("${path}${subPath}", (`); let params = []; if (method.parameters.length > 0) { for (let i = 0; i < method.parameters.length; ++i) { const param = method.parameters[i]; const type = translations.get(expandType(param.type)) || expandType(param.type); this.write( `${type} ${param.name}${ i != method.parameters.length - 1 ? ", " : "" }` ); params.push(param.name); } } this.write( `) => service.${pascalCase(method.name)}(${params.join(", ")}));\n` ); } this.write(` }\n }\n`); } } // Language: typescript