import { Name } from "../common/structures/name" ; import fs from "fs-extra" ; import path from "path" ; import { ramlToolLogger } from "../common/logger" ; import { TemplateDelegate } from "handlebars" ; import { HandlebarsWithAmfHelpers as Handlebars } from "./" ; description export class export class ApiMetadata { name : Name ; metadata : { [ key ] : unknown ; } = { } ; parent : ApiMetadata = null ; templates : { handlebarTemplate : TemplateDelegate ; outputFile : string ; } [ ] = [ ] ; param { string } name param { string } filepath param { ApiMetadata [ ] } children memberof constructor ( name , protected filepath = undefined , public children = [ ] ) { this . name = new Name ( name ) ; if ( filepath && fs . existsSync ( path . join ( filepath , `.metadata.json` ) ) ) { try { this . metadata = fs . readJSONSync ( path . join ( filepath , `.metadata.json` ) ) ; } catch ( e ) { ramlToolLogger . warn ( `Metadata found, but failed to load for ${ filepath }` ) ; } } children . forEach ( ( child ) => { child . parent = this ; } ) ; } description param { string } templatePath param { string } outputFile memberof public addTemplate ( templatePath , outputFile ) { this . templates . push ( { handlebarTemplate : Handlebars . compile ( fs . readFileSync ( path . join ( templatePath ) , "utf8" ) ) , outputFile , } ) ; } description returns { Promise < void > } memberof public async renderThis ( ) { ramlToolLogger . info ( `Rendering templates for ${ this . name . original }` ) ; const promises = this . templates . map ( async ( template ) => { try { await fs . ensureDir ( path . dirname ( template . outputFile ) ) ; await fs . writeFile ( template . outputFile , template . handlebarTemplate ( this , { allowProtoPropertiesByDefault : true , allowProtoMethodsByDefault : true , } ) ) ; } catch ( err ) { ramlToolLogger . error ( `Error while rendering ${ template . outputFile }:` , err ) ; } } ) ; await Promise . all ( promises ) ; } description returns { Promise < void > } memberof public async render ( ) { try { await this . renderThis ( ) ; } catch ( err ) { ramlToolLogger . error ( `Failed to render ${ this . name }:` , err ) ; } const promises = this . children . map ( async ( child ) => await child . render ( ) ) ; await Promise . all ( promises ) ; } description returns { Promise < void > } memberof public async init ( ) { const promises = this . children . map ( ( child ) => child . init ( ) ) ; await Promise . all ( promises ) ; } }