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: fixed data tags, description preset for Go, add goIncludeComments and goIncludeTags flags #2123

Open
wants to merge 7 commits into
base: next
Choose a base branch
from
Open
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
19 changes: 14 additions & 5 deletions docs/languages/Go.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ There are special use-cases that each language supports; this document pertains
<!-- toc is generated with GitHub Actions do not remove toc markers -->
<!-- toc -->

- [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality)
* [To and from JSON](#to-and-from-json)
* [To and from XML](#to-and-from-xml)
* [To and from binary](#to-and-from-binary)
- [Go](#go)
- [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality)
- [To and from JSON](#to-and-from-json)
- [JSON Tags](#json-tags)
- [To and from XML](#to-and-from-xml)
- [To and from binary](#to-and-from-binary)
- [Rendering comments from description and example fields](#rendering-comments-from-description-and-example-fields)

<!-- tocstop -->

Expand All @@ -24,7 +27,7 @@ Here are all the supported presets and the libraries they use for converting to

#### JSON Tags

To generate go models that work correctly with JSON marshal functions we need to generate appropriate JSON `struct-tags`, use the preset `GO_COMMON_PRESET` and provide the option `addJsonTag: true`.
To generate go models that work correctly with JSON marshal functions we need to generate appropriate JSON `struct-tags`, use the preset `GO_COMMON_PRESET` and provide the option `addJsonTag: true` (added in CLI by default).

check out this [example for a live demonstration](../../examples/go-json-tags/)

Expand All @@ -33,3 +36,9 @@ Currently not supported, [let everyone know you need it](https://github.com/asyn

### To and from binary
Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)!

## Rendering comments from description and example fields

You can use the `GO_DESCRIPTION_PRESET` to generate comments from description fields in your model.

See [this example](../../examples/generate-go-asyncapi-comments) for how this can be used.
17 changes: 17 additions & 0 deletions examples/generate-go-asyncapi-comments/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Go Data Models from AsyncAPI

A basic example of how to use Modelina and output a Go data model from AsyncAPI, including data tags and comments from description.

## 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,27 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Should be able to render Go Models and should log expected output to console 1`] = `
Array [
"// Payload for updating stock information
type StockUpdatePayload struct {
ProductId string \`json:\\"productId\\" binding:\\"required\\"\`
// The updated quantity of the product
Quantity int \`json:\\"quantity,omitempty\\"\`
// Warehouse location of the product
Location string \`json:\\"location,omitempty\\"\`
}",
]
`;

exports[`Should be able to render Go Models and should log expected output to console 2`] = `
Array [
"// Payload for low stock alerts
type LowStockPayload struct {
ProductId string \`json:\\"productId\\" binding:\\"required\\"\`
// The stock level threshold
Threshold int \`json:\\"threshold\\" binding:\\"required\\"\`
// The current stock level
CurrentStock int \`json:\\"currentStock,omitempty\\"\`
}",
]
`;
16 changes: 16 additions & 0 deletions examples/generate-go-asyncapi-comments/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const spy = jest.spyOn(global.console, 'log').mockImplementation(() => {
return;
});
import { generate } from './index';

describe('Should be able to render Go Models', () => {
afterAll(() => {
jest.restoreAllMocks();
});
test('and should log expected output to console', async () => {
await generate();
expect(spy.mock.calls.length).toEqual(2);
expect(spy.mock.calls[0]).toMatchSnapshot();
expect(spy.mock.calls[1]).toMatchSnapshot();
});
});
116 changes: 116 additions & 0 deletions examples/generate-go-asyncapi-comments/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import {
GoGenerator,
GO_DESCRIPTION_PRESET,
GO_COMMON_PRESET,
GoCommonPresetOptions
} from '../../src';

const options: GoCommonPresetOptions = { addJsonTag: true };
const generator = new GoGenerator({
presets: [GO_DESCRIPTION_PRESET, { preset: GO_COMMON_PRESET, options }]
});

const asyncAPIDocument = {
asyncapi: '3.0.0',
info: {
title: 'inventoryService',
version: '2.1.0'
},
channels: {
inventory: {
address: '/inventory',
messages: {
updateStock: {
summary: 'Update stock levels',
payload: {
title: 'stockUpdatePayload',
type: 'object',
description: 'Payload for updating stock information',
required: ['productId'],
additionalProperties: false,
properties: {
productId: {
type: 'string'
},
quantity: {
type: 'integer',
description: 'The updated quantity of the product'
},
location: {
type: 'string',
description: 'Warehouse location of the product'
}
}
}
}
}
},
alerts: {
address: '/alerts',
messages: {
lowStockAlert: {
summary: 'Low stock level alert',
payload: {
title: 'lowStockPayload',
type: 'object',
description: 'Payload for low stock alerts',
required: ['productId', 'threshold'],
additionalProperties: false,
properties: {
productId: {
type: 'string'
},
threshold: {
type: 'integer',
description: 'The stock level threshold'
},
currentStock: {
type: 'integer',
description: 'The current stock level'
}
}
}
}
}
}
},
operations: {
updateInventory: {
title: 'Update Inventory Operation',
summary: 'Operation to update inventory stock levels',
channel: {
$ref: '#/channels/inventory'
},
action: 'send',
messages: [
{
$ref: '#/channels/inventory/messages/updateStock'
}
]
},
notifyLowStock: {
title: 'Notify Low Stock Operation',
summary: 'Operation to notify when stock is low',
channel: {
$ref: '#/channels/alerts'
},
action: 'receive',
messages: [
{
$ref: '#/channels/alerts/messages/lowStockAlert'
}
]
}
}
};

export async function generate(): Promise<void> {
const models = await generator.generate(asyncAPIDocument);
for (const model of models) {
console.log(model.result);
}
}

if (require.main === module) {
generate();
}
10 changes: 10 additions & 0 deletions examples/generate-go-asyncapi-comments/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/generate-go-asyncapi-comments/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"example_name": "generate-go-asyncapi-comments"
},
"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"
}
}
9 changes: 3 additions & 6 deletions examples/generate-go-enums/__snapshots__/index.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

exports[`Should be able to render Go Enums and should log expected output to console 1`] = `
Array [
"// Root represents a Root model.
type Root struct {
"type Root struct {
Cities *Cities
Options *Options
}",
Expand All @@ -12,8 +11,7 @@ type Root struct {

exports[`Should be able to render Go Enums and should log expected output to console 2`] = `
Array [
"// Cities represents an enum of Cities.
type Cities uint
"type Cities uint

const (
CitiesLondon Cities = iota
Expand Down Expand Up @@ -41,8 +39,7 @@ var ValuesToCities = map[any]Cities{

exports[`Should be able to render Go Enums and should log expected output to console 3`] = `
Array [
"// Options represents an enum of Options.
type Options uint
"type Options uint

const (
OptionsNumber_123 Options = iota
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

exports[`Should be able to render Go Models and should log expected output to console 1`] = `
Array [
"// Root represents a Root model.
type Root struct {
"type Root struct {
Email string
}",
]
Expand Down
9 changes: 3 additions & 6 deletions examples/go-json-tags/__snapshots__/index.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

exports[`Should be able to render json-tags in struct and should log expected output to console 1`] = `
Array [
"// Root represents a Root model.
type Root struct {
"type Root struct {
Cities *Cities \`json:\\"cities,omitempty\\"\`
Options *Options \`json:\\"options,omitempty\\"\`
}",
Expand All @@ -12,8 +11,7 @@ type Root struct {

exports[`Should be able to render json-tags in struct and should log expected output to console 2`] = `
Array [
"// Cities represents an enum of Cities.
type Cities uint
"type Cities uint

const (
CitiesLondon Cities = iota
Expand Down Expand Up @@ -54,8 +52,7 @@ func (op Cities) MarshalJSON() ([]byte, error) {

exports[`Should be able to render json-tags in struct and should log expected output to console 3`] = `
Array [
"// Options represents an enum of Options.
type Options uint
"type Options uint

const (
OptionsNumber_123 Options = iota
Expand Down
15 changes: 5 additions & 10 deletions examples/go-union-type/__snapshots__/index.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

exports[`Should be able to render union types and should log expected output to console 1`] = `
Array [
"// AdditionalProperty represents a AdditionalProperty model.
type AdditionalProperty struct {
"type AdditionalProperty struct {
AdditionalPropertyOneOf_0
AdditionalPropertyOneOf_1
string
Expand All @@ -17,8 +16,7 @@ type AdditionalProperty struct {

exports[`Should be able to render union types and should log expected output to console 2`] = `
Array [
"// Union represents a Union model.
type Union struct {
"type Union struct {
string
float64
ModelinaAnyType interface{}
Expand All @@ -28,8 +26,7 @@ type Union struct {

exports[`Should be able to render union types and should log expected output to console 3`] = `
Array [
"// AdditionalPropertyOneOf_6 represents a AdditionalPropertyOneOf_6 model.
type AdditionalPropertyOneOf_6 struct {
"type AdditionalPropertyOneOf_6 struct {
string
float64
bool
Expand All @@ -45,8 +42,7 @@ Array [

exports[`Should be able to render union types and should log expected output to console 5`] = `
Array [
"// AdditionalPropertyOneOf_0 represents a AdditionalPropertyOneOf_0 model.
type AdditionalPropertyOneOf_0 struct {
"type AdditionalPropertyOneOf_0 struct {
Ref string
AdditionalProperties map[string]interface{}
}",
Expand All @@ -55,8 +51,7 @@ type AdditionalPropertyOneOf_0 struct {

exports[`Should be able to render union types and should log expected output to console 6`] = `
Array [
"// AdditionalPropertyOneOf_1 represents a AdditionalPropertyOneOf_1 model.
type AdditionalPropertyOneOf_1 struct {
"type AdditionalPropertyOneOf_1 struct {
Id string
AdditionalProperties map[string]interface{}
}",
Expand Down
3 changes: 2 additions & 1 deletion modelina-cli/.eslintignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/lib
/tmp
/scripts
/test/helpers/init.js
/test/helpers/init.js
/test/fixtures/generate
4 changes: 2 additions & 2 deletions modelina-cli/src/commands/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ export default class Models extends ModelinaCommand {
try {
document = await readFile(file, 'utf8');
} catch {
throw new Error('Unable to read input file content.');
throw new Error(`Unable to read input file content: ${file}`);
}

const logger = {
info: (message: string) => {
this.log(message);
Expand Down
Loading
Loading