Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add components library #1315

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ apps/generator/output/*
.github/templates-list-validator/dist/*
apps/generator/test/temp/*
apps/generator/test/test-templates/react-template/__transpiled/*

apps/components/lib/*
1 change: 1 addition & 0 deletions apps/components/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/lib
57 changes: 57 additions & 0 deletions apps/components/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "@asyncapi/generator-components",
"version": "1.0.0",
"description": "Package with reusable components for generation using React render engine",
"scripts": {
"test": "jest --coverage",
"test:update": "jest --coverage -u",
"build": "babel src --out-dir lib",
"prepublishOnly": "npm run build",
"lint": "eslint --max-warnings 0 --config ../../.eslintrc --ignore-path ../../.eslintignore .",
"lint:fix": "eslint --max-warnings 0 --config ../../.eslintrc --ignore-path ../../.eslintignore . --fix",
"generate:assets": "npm run prepublishOnly"
},
"main": "lib/index.js",
"repository": {
"type": "git",
"url": "https://github.com/asyncapi/generator/apps/components"
},
"author": "Lukasz Gornicki",
"license": "Apache-2.0",
"dependencies": {
"@asyncapi/generator-react-sdk": "^1.1.2",
"@asyncapi/modelina": "^4.0.0-next.62"
},
"devDependencies": {
"@babel/cli": "^7.25.9",
"@babel/core": "^7.26.0",
"@babel/preset-env": "^7.26.0",
"@babel/preset-react": "^7.25.9",
"jest-esm-transformer": "^1.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"jsx"
],
"transform": {
"^.+\\.jsx?$": "babel-jest"
},
"moduleNameMapper": {
"^nimma/legacy$": "<rootDir>/../../node_modules/nimma/dist/legacy/cjs/index.js",
"^nimma/(.*)": "<rootDir>/../../node_modules/nimma/dist/cjs/$1"
}
},
"babel": {
"presets": [
"@babel/preset-env",
[
"@babel/preset-react",
{
"runtime": "automatic"
}
]
]
}
}
75 changes: 75 additions & 0 deletions apps/components/src/components/models.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { File } from '@asyncapi/generator-react-sdk';
import {
PythonGenerator,
JavaGenerator,
TypeScriptGenerator,
CSharpGenerator,
RustGenerator,
FormatHelpers
} from '@asyncapi/modelina';

/**
* @typedef {'toPascalCase' | 'toCamelCase' | 'toKebabCase' | 'toSnakeCase'} Format
* Represents the available format helpers for naming files.
*/

/**
* @typedef {'python' | 'java' | 'typescript' | 'rust' | 'csharp'} Language
* Represents the available programming languages for model generation.
*/

/**
* Mapping of language strings to Modelina generator classes and file extensions.
* @type {Record<string, { generator: new (options?: object) => any; extension: string }>}
*/
const generatorConfig = {
python: { generator: PythonGenerator, extension: 'py' },
java: { generator: JavaGenerator, extension: 'java' },
typescript: { generator: TypeScriptGenerator, extension: 'ts' },
rust: { generator: RustGenerator, extension: 'rs' },
csharp: { generator: CSharpGenerator, extension: 'cs' },
};

/**
* Mapping of available format functions.
*/
const formatHelpers = {
toPascalCase: FormatHelpers.toPascalCase,
toCamelCase: FormatHelpers.toCamelCase,
toKebabCase: FormatHelpers.toKebabCase,
toSnakeCase: FormatHelpers.toSnakeCase,
// Add more formats as needed
};

/**
* Generates and returns an array of model files based on the AsyncAPI document.
*
* @param {Object} params - The parameters for the function.
* @param {AsyncAPIDocumentInterface} params.asyncapi - Parsed AsyncAPI document object.
* @param {Language} [params.language='python'] - Target programming language for the generated models.
* @param {Format} [params.format='toPascalCase'] - Naming format for generated files.
* @param {object} [params.presets={}] - Custom presets for the generator instance.
* @param {object} [params.constraints={}] - Custom constraints for the generator instance.
*
* @returns {Array<File>} Array of File components with generated model content.
*/
export async function Models({ asyncapi, language = 'python', format = 'toPascalCase', presets, constraints }) {
// Get the selected generator and file extension, defaulting to Python if unknown
const { generator: GeneratorClass, extension } = generatorConfig[language] || generatorConfig.python;

// Create the generator instance with presets and constraints
const generator = (presets || constraints)
? new GeneratorClass({ ...(presets && { presets }), ...(constraints && { constraints }) })
: new GeneratorClass();

// Get the format helper function, defaulting to toPascalCase if unknown
const formatHelper = formatHelpers[format] || formatHelpers.toPascalCase;

// Generate models asynchronously
const models = await generator.generate(asyncapi);

return models.map(model => {
const modelFileName = `${formatHelper(model.modelName)}.${extension}`;
return <File name={modelFileName}>{model.result}</File>;
});
}
1 change: 1 addition & 0 deletions apps/components/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { Models } from './components/models';
34 changes: 34 additions & 0 deletions apps/components/test/__fixtures__/asyncapi-v3.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
asyncapi: 3.0.0
info:
title: Account Service
version: 1.0.0
description: This service is in charge of processing user signups
channels:
userSignedup:
address: user/signedup
messages:
UserSignedUp:
$ref: '#/components/messages/UserSignedUp'
operations:
sendUserSignedup:
action: send
channel:
$ref: '#/channels/userSignedup'
messages:
- $ref: '#/channels/userSignedup/messages/UserSignedUp'
components:
schemas:
UserSignedUp:
type: object
properties:
displayName:
type: string
description: Name of the user
email:
type: string
format: email
description: Email of the user
messages:
UserSignedUp:
payload:
$ref: '#/components/schemas/UserSignedUp'
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Integration Tests for models function renders Csharp models 1`] = `
Array [
<File
name="UserSignedUp.cs"
>
public partial class UserSignedUp
{
private string? displayName;
private string? email;
private Dictionary&lt;string, dynamic&gt;? additionalProperties;

public string? DisplayName
{
get { return displayName; }
set { this.displayName = value; }
}

public string? Email
{
get { return email; }
set { this.email = value; }
}

public Dictionary&lt;string, dynamic&gt;? AdditionalProperties
{
get { return additionalProperties; }
set { this.additionalProperties = value; }
}
}
</File>,
]
`;

exports[`Integration Tests for models function renders default as Python models 1`] = `
Array [
<File
name="UserSignedUp.py"
>
class UserSignedUp:
def __init__(self, input: Dict):
if 'display_name' in input:
self._display_name: str = input['display_name']
if 'email' in input:
self._email: str = input['email']
if 'additional_properties' in input:
self._additional_properties: dict[str, Any] = input['additional_properties']

@property
def display_name(self) -&gt; str:
return self._display_name
@display_name.setter
def display_name(self, display_name: str):
self._display_name = display_name

@property
def email(self) -&gt; str:
return self._email
@email.setter
def email(self, email: str):
self._email = email

@property
def additional_properties(self) -&gt; dict[str, Any]:
return self._additional_properties
@additional_properties.setter
def additional_properties(self, additional_properties: dict[str, Any]):
self._additional_properties = additional_properties

</File>,
]
`;
27 changes: 27 additions & 0 deletions apps/components/test/components/models.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import path from 'path';
import { Models } from '../../src/index';
import { Parser, fromFile } from '@asyncapi/parser';

const parser = new Parser();
const asyncapi_v3_path = path.resolve(__dirname, '../__fixtures__/asyncapi-v3.yml');

describe('Integration Tests for models function', () => {
let parsedAsyncAPIDocument;

beforeAll(async () => {
const parseResult = await fromFile(parser, asyncapi_v3_path).parse();
parsedAsyncAPIDocument = parseResult.document;
});

test('renders default as Python models', async () => {
const result = await Models({asyncapi: parsedAsyncAPIDocument});

expect(result).toMatchSnapshot();
});

test('renders Csharp models', async () => {
const result = await Models({asyncapi: parsedAsyncAPIDocument, language: 'csharp'});

expect(result).toMatchSnapshot();
});
});
1 change: 1 addition & 0 deletions apps/generator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"license": "Apache-2.0",
"homepage": "https://github.com/asyncapi/generator",
"dependencies": {
"@asyncapi/generator-components": "*",
"@asyncapi/generator-react-sdk": "^1.1.2",
"@asyncapi/multi-parser": "^2.1.1",
"@asyncapi/nunjucks-filters": "*",
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Models } from '@asyncapi/generator-components';

export default async function({ asyncapi }) {
return await Models({asyncapi, language: 'csharp'});
}
Loading
Loading