Skip to content

Commit

Permalink
adding first component and test for it
Browse files Browse the repository at this point in the history
  • Loading branch information
derberg committed Oct 30, 2024
1 parent d110189 commit 02f9067
Show file tree
Hide file tree
Showing 16 changed files with 342 additions and 58 deletions.
5 changes: 0 additions & 5 deletions apps/components/index.js

This file was deleted.

44 changes: 0 additions & 44 deletions apps/components/models.js

This file was deleted.

35 changes: 33 additions & 2 deletions apps/components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
"name": "@asyncapi/generator-components",
"version": "1.0.0",
"description": "Package with reusable components for generation using React render engine",
"main": "index.js",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest --coverage"
},
"repository": {
"type": "git",
Expand All @@ -15,5 +15,36 @@
"dependencies": {
"@asyncapi/generator-react-sdk": "^1.1.2",
"@asyncapi/modelina": "^4.0.0-next.62"
},
"devDependencies": {
"jest-esm-transformer": "^1.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"jsx"
],
"setupFilesAfterEnv": [
"./test/setupTests.js"
],
"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"
}
]
]
}
}
76 changes: 76 additions & 0 deletions apps/components/src/components/models.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { File } from '@asyncapi/generator-react-sdk';
import { AsyncAPIDocumentInterface } from '@asyncapi/parser';
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'
40 changes: 40 additions & 0 deletions apps/components/test/components/__snapshots__/models.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Integration Tests for models function renders default as Python models correctly 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>,
]
`;
21 changes: 21 additions & 0 deletions apps/components/test/components/models.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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 correctly', async () => {
const result = await Models({asyncapi: parsedAsyncAPIDocument});

expect(result).toMatchSnapshot();
});
});
1 change: 1 addition & 0 deletions apps/components/test/setupTests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'regenerator-runtime/runtime';
1 change: 1 addition & 0 deletions apps/generator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@asyncapi/generator-react-sdk": "^1.1.2",
"@asyncapi/multi-parser": "^2.1.1",
"@asyncapi/nunjucks-filters": "*",
"@asyncapi/generator-components": "*",
"@asyncapi/parser": "^3.0.14",
"@npmcli/arborist": "5.6.3",
"@npmcli/config": "^8.0.2",
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.

Loading

0 comments on commit 02f9067

Please sign in to comment.