Skip to content

Commit

Permalink
chore: merge branch master into next
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaslagoni committed Feb 13, 2024
2 parents 6d9c2c8 + 11e2053 commit 71b7759
Show file tree
Hide file tree
Showing 42 changed files with 793 additions and 319 deletions.
10 changes: 10 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,16 @@
"contributions": [
"doc"
]
},
{
"login": "RowlandBanks",
"name": "RowlandBanks",
"avatar_url": "https://avatars.githubusercontent.com/u/9962551?v=4",
"profile": "https://github.com/RowlandBanks",
"contributions": [
"code",
"test"
]
}
],
"contributorsPerLine": 7,
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
[![Discussions](https://img.shields.io/github/discussions/asyncapi/modelina)](https://github.com/asyncapi/modelina/discussions)
[![Website](https://img.shields.io/website?label=website&url=https%3A%2F%2Fwww.modelina.org)](https://www.modelina.org)
[![Playground](https://img.shields.io/website?label=playground&url=https%3A%2F%2Fwww.modelina.org%2Fplayground)](https://www.modelina.org/playground) <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-77-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-78-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

Your one-stop tool for generating accurate and well-tested models for representing the message payloads. Use it as a tool in your development workflow, or a library in a larger integrations, entirely in your control.
Expand Down Expand Up @@ -422,6 +422,9 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org
<td align="center" valign="top" width="14.28%"><a href="https://github.com/officialasishkumar"><img src="https://avatars.githubusercontent.com/u/87874775?v=4?s=100" width="100px;" alt="Asish Kumar"/><br /><sub><b>Asish Kumar</b></sub></a><br /><a href="https://github.com/asyncapi/modelina/commits?author=officialasishkumar" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/ankur0904"><img src="https://avatars.githubusercontent.com/u/98346896?v=4?s=100" width="100px;" alt="Ankur Singh"/><br /><sub><b>Ankur Singh</b></sub></a><br /><a href="https://github.com/asyncapi/modelina/commits?author=ankur0904" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/RowlandBanks"><img src="https://avatars.githubusercontent.com/u/9962551?v=4?s=100" width="100px;" alt="RowlandBanks"/><br /><sub><b>RowlandBanks</b></sub></a><br /><a href="https://github.com/asyncapi/modelina/commits?author=RowlandBanks" title="Code">💻</a> <a href="https://github.com/asyncapi/modelina/commits?author=RowlandBanks" title="Tests">⚠️</a></td>
</tr>
</tbody>
</table>

Expand Down
1 change: 1 addition & 0 deletions docs/generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ Below is a list of additional options available for a given generator.
| Option | Type | Description | Default value |
|---|---|---|---|
| `renderTypes` | Boolean | Render signature for types. | `true` |
| `mapType` | String | It indicates which mapping type should be rendered for the `object` type. Its value can be one of `map`, `record` or `indexedObject`. | `map` |
| `modelType` | String | It indicates which model type should be rendered for the `object` type. Its value can be either `interface` or `class`. | `class` |
| `enumType` | String | It indicates which type should be rendered for the `enum` type. Its value can be either `union` or `enum`. | `enum` |
| `namingConvention` | Object | Options for naming conventions. | - |
Expand Down
24 changes: 24 additions & 0 deletions docs/languages/TypeScript.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ There are special use-cases that each language supports; this document pertains
<!-- toc -->

- [Generate an interface instead of classes](#generate-an-interface-instead-of-classes)
- [Generate different `mapType`s for an `object`](#generate-different-maptypes-for-an-object)
- [Generate union types instead of enums](#generate-union-types-instead-of-enums)
- [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality)
* [To and from JSON](#to-and-from-json)
Expand All @@ -27,6 +28,29 @@ Sometimes you don't care about classes, but rather have interfaces generated. Th

Check out this [example out for a live demonstration](../../examples/typescript-interface).

## Generate different `mapType`s for an `object`

Typescript offers different `mapType`s which can simplify the use based on the needs. This behavior can be changed through the [`mapType` configuration](https://github.com/asyncapi/modelina/blob/master/docs/generators.md#typescript).

- Use `map` when you need a dynamic collection of key-value pairs with built-in methods for manipulation.
- Use `record` when you want to define an object with specific keys and their corresponding value types.
- Use `indexedObject` (or an interface with index signature) for a more generic approach when working with objects with dynamic keys.

An example of the generated code can be seen below:

```ts
// mapType = indexedObject
private _person?: { [name: string]: any };

// mapType = map
private _person?: Map<string, any>;

// mapType = record
private _person?: Record<string, any>;
```

Also, check out this [example for a live demonstration](../../examples/typescript-change-map-type).

## Generate union types instead of enums

Typescript offers union types which can simplify the use as no keywords are needed and the values can be set directly. This behavior can be changed through the [modelType configuration](https://github.com/asyncapi/modelina/blob/master/docs/generators.md#typescript). An example of the generated code can be seen below:
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ These are all specific examples only relevant to the C# generator:
### TypeScript
These are all specific examples only relevant to the TypeScript generator:

- [typescript-change-map-type](./typescript-change-map-type) - A basic example showing the use of `mapType` options.
- [generate-typescript-models](./generate-typescript-models) - A basic example to generate TypeScript data models
- [typescript-interface](./typescript-interface) - A basic TypeScript generator that outputs interfaces.
- [typescript-enum-type](./typescript-enum-type) - A basic example of how to use Modelina can output different types of enums in TypeScript.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to generate a model with custom input and output and should log expected output to console 1`] = `
Array [
"public class Address
"public partial class Address
{
public Dictionary<string, object> dictionaryProp;
}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to render auto-implemented properties in CSharp and should log expected output to console 1`] = `
Array [
"public class Root
"public partial class Root
{
public string[]? Emails { get; set; }
public string? StringProp { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to render collections in C# as IEnumerable and should log expected output to console 1`] = `
Array [
"public class Root
"public partial class Root
{
private IEnumerable<string>? email;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to generate a model to overwrite the Equal and GetHashCode methods and should log expected output to console 1`] = `
Array [
"public class Root
"public partial class Root
{
private string? email;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to render a C# class with null warning removed with handleNullable option and should log expected output to console 1`] = `
Array [
"public class Root
"public partial class Root
{
public string? Email { get; set; }
public string Name { get; set; } = null!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
exports[`Should be able to generate a model with functions to serialize the data model into JSON and should log expected output to console 1`] = `
Array [
"[JsonConverter(typeof(RootConverter))]
public class Root
public partial class Root
{
private string? email;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
exports[`Should be able to generate a model with functions to serialize the data model into JSON and should log expected output to console 1`] = `
Array [
"[JsonConverter(typeof(RootConverter))]
public class Root
public partial class Root
{
private string? email;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to render a C# record instead of a class using the modelType option and should log expected output to console 1`] = `
Array [
"public record Root
"public partial record Root
{
public IEnumerable<string>? Email { get; init; }
public required string Name { get; init; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to render required properties without the question mark at the end if the type of it is not nullable and should log expected output to console 1`] = `
Array [
"public class Root
"public partial class Root
{
private bool requiredBoolean;
private bool? notRequiredBoolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

exports[`Should be able to render C# models and should log expected output to console 1`] = `
Array [
"public class Root
"public partial class Root
{
private string? email;
private System.DateTime? today;
Expand Down
17 changes: 17 additions & 0 deletions examples/typescript-change-map-type/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# TypeScript Map Types

A basic example showing the use of `mapType` options.

## How to run this example

Run this example using:

```sh
npm i && npm run start
```

If you are on Windows, use the `start:windows` script instead:

```sh
npm i && npm run start:windows
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Should be able to render correct map type based on options and should log expected output to console 1`] = `
"// Generator output as indexedObject
class Root {
private _person?: { [name: string]: any };
constructor(input: {
person?: { [name: string]: any },
}) {
this._person = input.person;
}
get person(): { [name: string]: any } | undefined { return this._person; }
set person(person: { [name: string]: any } | undefined) { this._person = person; }
}
// Generator output as Map
class Root {
private _person?: Map<string, any>;
constructor(input: {
person?: Map<string, any>,
}) {
this._person = input.person;
}
get person(): Map<string, any> | undefined { return this._person; }
set person(person: Map<string, any> | undefined) { this._person = person; }
}
// Generator output as Record
class Root {
private _person?: Record<string, any>;
constructor(input: {
person?: Record<string, any>,
}) {
this._person = input.person;
}
get person(): Record<string, any> | undefined { return this._person; }
set person(person: Record<string, any> | undefined) { this._person = person; }
}"
`;
15 changes: 15 additions & 0 deletions examples/typescript-change-map-type/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const spy = jest.spyOn(global.console, 'log').mockImplementation(() => {
return;
});
import { generate } from './index';

describe('Should be able to render correct map type based on options', () => {
afterAll(() => {
jest.restoreAllMocks();
});
test('and should log expected output to console', async (): Promise<void> => {
await generate();
expect(spy.mock.calls.length).toEqual(6);
expect(spy.mock.calls.join('\n')).toMatchSnapshot();
});
});
50 changes: 50 additions & 0 deletions examples/typescript-change-map-type/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { TypeScriptGenerator } from '../../src';

const generatorIndexedObject = new TypeScriptGenerator({
mapType: 'indexedObject'
});
const generatorMap = new TypeScriptGenerator({ mapType: 'map' });
const generatorRecord = new TypeScriptGenerator({ mapType: 'record' });

const jsonSchemaDraft7 = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
additionalProperties: false,
properties: {
person: {
type: 'object',
personName: { type: 'string' },
email: {
type: 'string',
format: 'email'
},
isStudent: { type: 'boolean' },
age: { type: 'number' }
}
}
};

export async function generate(): Promise<void> {
console.log('// Generator output as indexedObject');
const modelsIndexedObject =
await generatorIndexedObject.generate(jsonSchemaDraft7);
for (const model of modelsIndexedObject) {
console.log(model.result);
}

console.log('// Generator output as Map');
const modelsMap = await generatorMap.generate(jsonSchemaDraft7);
for (const model of modelsMap) {
console.log(model.result);
}

console.log('// Generator output as Record');
const modelsRecord = await generatorRecord.generate(jsonSchemaDraft7);
for (const model of modelsRecord) {
console.log(model.result);
}
}

if (require.main === module) {
generate();
}
10 changes: 10 additions & 0 deletions examples/typescript-change-map-type/package-lock.json

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

12 changes: 12 additions & 0 deletions examples/typescript-change-map-type/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"example_name": "typescript-change-map-type"
},
"scripts": {
"install": "cd ../.. && npm i",
"start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts",
"start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts",
"test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts",
"test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ModelinaPhpOptions,
ModelinaPythonOptions,
ModelinaRustOptions,
ModelinaScalaOptions,
ModelinaTypeScriptOptions
} from '@/types';
import { createContext } from 'react';
Expand All @@ -24,6 +25,8 @@ export const PlaygroundGoConfigContext =
createContext<ModelinaGoOptions | null>(null);
export const PlaygroundRustConfigContext =
createContext<ModelinaRustOptions | null>(null);
export const PlaygroundScalaConfigContext =
createContext<ModelinaScalaOptions | null>(null);
export const PlaygroundKotlinConfigContext =
createContext<ModelinaKotlinOptions | null>(null);
export const PlaygroundDartConfigContext =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ export const PlaygroundContextProvider: React.FC<{ children: React.ReactNode; }>
javaOverwriteToString: false,
javaJavaDocs: false,
javaJavaxAnnotation: false,
scalaCollectionType: 'Array',
scalaPackageName: 'asyncapi.models',
goPackageName: 'asyncapi.models',
kotlinPackageName: 'asyncapi.models'
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
PlaygroundJavaScriptConfigContext,
PlaygroundKotlinConfigContext,
PlaygroundPythonConfigContext,
PlaygroundScalaConfigContext,
PlaygroundRustConfigContext,
PlaygroundCplusplusConfigContext,
PlaygroundGeneralConfigContext,
Expand Down Expand Up @@ -35,9 +36,11 @@ export const OptionsNavigation: React.FunctionComponent<OptionsNavigationProps>
<PlaygroundCplusplusConfigContext.Provider value={config}>
<PlaygroundKotlinConfigContext.Provider value={config}>
<PlaygroundRustConfigContext.Provider value={config}>
<PlaygroundPythonConfigContext.Provider value={config}>
<PlaygroundOptions setNewConfig={setNewConfig} />
</PlaygroundPythonConfigContext.Provider>
<PlaygroundScalaConfigContext.Provider value={config}>
<PlaygroundPythonConfigContext.Provider value={config}>
<PlaygroundOptions setNewConfig={setNewConfig} />
</PlaygroundPythonConfigContext.Provider>
</PlaygroundScalaConfigContext.Provider>
</PlaygroundRustConfigContext.Provider>
</PlaygroundKotlinConfigContext.Provider>
</PlaygroundCplusplusConfigContext.Provider>
Expand Down
Loading

0 comments on commit 71b7759

Please sign in to comment.