Last active
October 24, 2025 10:02
-
-
Save WhereJuly/1cadad5a60adf13caa0599655b63c26b to your computer and use it in GitHub Desktop.
AsyncAPI Modelina custom property names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| import fs from 'node:fs/promises'; | |
| import path from 'node:path'; | |
| import { Parser, fromFile } from '@asyncapi/parser'; | |
| import { PropertyKeyContext, TypeScriptGenerator } from '@asyncapi/modelina'; | |
| /** | |
| * Modelina by default transforms payload properties' names into `camelCase`. This custom sctript | |
| * retirns the property names as-is keeping your `snake_case` naming in place. | |
| */ | |
| async function main() { | |
| // Extract these into the script parameters. | |
| const src = `${process.cwd()}/src/project.a2s.json`; | |
| const dest = `${process.cwd()}/destination/models`; | |
| // 1. Parse the AsyncAPI / A2S document | |
| const parser = new Parser(); | |
| const { document: asyncapiDoc } = await fromFile(parser, src).parse(); | |
| if (!asyncapiDoc) { | |
| throw new Error(`Failed to parse document at ${src}`); | |
| } | |
| // 2. Create Modelina generator with the settings you want | |
| const generator = new TypeScriptGenerator({ | |
| modelType: 'interface', | |
| /** | |
| * There was solution advised to fix the snake case issue. | |
| * The solution is not working, at least in "@asyncapi/modelina": "^5.10.1" | |
| * @see https://github.com/asyncapi/modelina/issues/885 | |
| * | |
| * The working solution is below. | |
| */ | |
| constraints: { | |
| propertyKey: (context: PropertyKeyContext<any>) => { | |
| return context.objectPropertyModel.propertyName; | |
| } | |
| } | |
| }); | |
| // 3. Generate models | |
| const models = await generator.generateCompleteModels(asyncapiDoc, {exportType: 'default'}); | |
| // 4. Write each generated model to the output directory | |
| await fs.mkdir(dest, { recursive: true }); | |
| await Promise.all(models.map(async model => { | |
| const filePath = path.join(dest, `${model.modelName}.ts`); | |
| await fs.writeFile(filePath, model.result, 'utf8'); | |
| console.log(`Generated model: ${filePath}`); | |
| })); | |
| console.log('Generation completed successfully.'); | |
| } | |
| try { | |
| await main(); | |
| } catch (error) { | |
| console.error('Error generating models:', error); | |
| process.exit(1); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment