/* Copyright 2022 The Apex Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Alias, AnyType, BaseVisitor, Context, Kind, List, Map, Optional, Primitive, PrimitiveName, Type, } from "@apexlang/core/model"; import { capitalize, convertOperationToType, isKinds, isObject, isService, unwrapKinds, } from "../utils/index.js"; import { getMethods, getPath, hasBody } from "../rest/index.js"; import { StructVisitor } from "./struct_visitor.js"; import { expandType, fieldName, methodName } from "./helpers.js"; import { Import, translateAlias } from "./alias_visitor.js"; export class FiberVisitor extends BaseVisitor { visitNamespaceBefore(context: Context): void { const packageName = context.config.package || "module"; this.write(`// Code generated by @apexlang/codegen. DO NOT EDIT. package ${packageName} import ( "github.com/gofiber/fiber/v2"\n`); const importsVisitor = new ImportsVisitor(this.writer); context.namespace.accept(context, importsVisitor); this.write(` "github.com/apexlang/api-go/transport/tfiber" "github.com/apexlang/api-go/transport/httpresponse" ) const _ = httpresponse.Package \n\n`); super.triggerNamespaceBefore(context); } visitInterfaceBefore(context: Context): void { if (!isService(context)) { return; } const { interface: iface } = context; const visitor = new FiberServiceVisitor(this.writer); iface.accept(context, visitor); } } class FiberServiceVisitor extends BaseVisitor { visitInterfaceBefore(context: Context): void { const { interface: iface } = context; this .write(`func ${iface.name}Fiber(service ${iface.name}) tfiber.RegisterFn { return func(router fiber.Router) {\n`); } visitOperation(context: Context): void { const { interface: iface, operation } = context; const path = getPath(context); if (path == "") { return; } const fiberPath = path.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g, ":$1"); const methods = getMethods(operation).map((m) => capitalize(m.toLowerCase()) ); const translate = translateAlias(context); methods.forEach((method) => { let paramType: AnyType | undefined; this.write( `router.${method}("${fiberPath}", func(c *fiber.Ctx) error { resp := httpresponse.New() ctx := httpresponse.NewContext(c.Context(), resp)\n` ); if (operation.isUnary()) { // TODO: check type paramType = operation.parameters[0].type; } else if (operation.parameters.length > 0) { const argsType = convertOperationToType( context.getType.bind(context), iface, operation ); paramType = argsType; const structVisitor = new StructVisitor(this.writer); argsType.accept(context.clone({ type: argsType }), structVisitor); } const operMethod = methodName(operation, operation.name); if (paramType) { // TODO this.write( `var args ${expandType(paramType, undefined, false, translate)}\n` ); if (hasBody(method)) { this.write(`if err := c.BodyParser(&args); err != nil { return err }\n`); } switch (paramType.kind) { case Kind.Type: const t = paramType as Type; t.fields.forEach((f) => { if (path.indexOf(`{${f.name}}`) != -1) { // Set path argument this.write( `args.${fieldName(f, f.name)} = c.Params("${f.name}")\n` ); } else if (f.annotation("query") != undefined) { this.write( `args.${fieldName(f, f.name)} = c.Query("${f.name}")\n` ); } }); break; } if (operation.type.kind != Kind.Void) { this.write(`result, `); } if (operation.isUnary()) { const pt = unwrapKinds(paramType, Kind.Alias); const share = isKinds(pt, Kind.Primitive, Kind.Enum) ? "" : "&"; this.write(`err := service.${operMethod}(ctx, ${share}args)\n`); } else { const args = (paramType as Type).fields .map( (f) => `, ${isObject(f.type, false) ? "&" : ""}args.${fieldName( f, f.name )}` ) .join(""); this.write(`err := service.${operMethod}(ctx${args})\n`); } } else { this.write(`err := service.${operMethod}(ctx)\n`); } if (operation.type.kind != Kind.Void) { this.write(`return tfiber.Response(c, resp, result, err)\n`); } else { this.write(`return err\n`); } this.write(`})\n`); }); } visitInterfaceAfter(context: Context): void { this.write(` } }\n`); } } class ImportsVisitor extends BaseVisitor { private imports: { [key: string]: Import } = {}; private externalImports: { [key: string]: Import } = {}; visitNamespaceAfter(context: Context): void { const stdLib = []; for (const key in this.imports) { const i = this.imports[key]; if (i.import) { stdLib.push(i.import); } } stdLib.sort(); for (const lib of stdLib) { this.write(`\t"${lib}"\n`); } const thirdPartyLib = []; for (const key in this.externalImports) { const i = this.externalImports[key]; if (i.import) { thirdPartyLib.push(i.import); } } thirdPartyLib.sort(); if (thirdPartyLib.length > 0) { this.write(`\n`); } for (const lib of thirdPartyLib) { this.write(`\t"${lib}"\n`); } } addType(name: string, i: Import) { if (i == undefined || i.import == undefined) { return; } if (i.import.indexOf(".") != -1) { if (this.externalImports[name] === undefined) { this.externalImports[name] = i; } } else { if (this.imports[name] === undefined) { this.imports[name] = i; } } } checkType(context: Context, type: AnyType): void { const aliases = (context.config.aliases as { [key: string]: Import }) || {}; switch (type.kind) { case Kind.Alias: { const a = type as Alias; const i = aliases[a.name]; this.addType(a.name, i); break; } case Kind.Primitive: const prim = type as Primitive; switch (prim.name) { case PrimitiveName.DateTime: this.addType("Time", { type: "time.Time", import: "time", }); break; } break; case Kind.Type: const named = type as Type; const i = aliases[named.name]; if (named.name === "datetime" && i == undefined) { this.addType("Time", { type: "time.Time", import: "time", }); return; } this.addType(named.name, i); break; case Kind.List: const list = type as List; this.checkType(context, list.type); break; case Kind.Map: const map = type as Map; this.checkType(context, map.keyType); this.checkType(context, map.valueType); break; case Kind.Optional: const optional = type as Optional; this.checkType(context, optional.type); break; case Kind.Enum: break; } } visitParameter(context: Context): void { this.checkType(context, context.parameter.type); } visitOperation(context: Context): void { this.checkType(context, context.operation.type); } }