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

docs: add example to use custom enum value name #764

Merged
Merged
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
8 changes: 8 additions & 0 deletions docs/languages/Csharp.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ There are special use-cases that each language supports; this document pertains
- [Generate models with equals and GetHashCode methods](#generate-models-with-equals-and-gethashcode-methods)
- [Generate models with auto-implemented properties](#generate-models-with-auto-implemented-properties)
- [Change the collection type for arrays](#change-the-collection-type-for-arrays)
- [Generate custom enum value names](#generate-custom-enum-value-names)
- [Generate models with inheritance](#generate-models-with-inheritance)

<!-- tocstop -->
Expand Down Expand Up @@ -41,8 +42,15 @@ If you consider the Array Class to be insuitable for your situation, then you mi

Check out this [example for a live demonstration](../../examples/csharp-change-collection-type).

## Generate custom enum value names

When using AsyncAPI or JSON Schema, it is not possible to associate enum names with values however with extensions it is.

Check out this [example for a live demonstration](../../examples/csharp-overwrite-enum-naming/).

## Generate models with inheritance

If you want the generated models to inherit from a custom class, you can overwrite the existing rendering behavior and create your own class setup.

Check out this [example for a live demonstration](../../examples/csharp-use-inheritance).

1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ This directory contains a series of self-contained examples that you can use as
- [java-generate-tostring](./java-generate-tostring) - A basic example that shows how to generate models that overwrite the `toString` method
- [csharp-generate-equals-and-hashcode](./csharp-generate-equals-and-hashcode) - A basic example on how to generate models that overwrite the `Equal` and `GetHashCode` methods
- [csharp-generate-serializer](./csharp-generate-serializer) - A basic example on how to generate models that include function to serialize the data models to JSON
- [csharp-overwrite-enum-naming](./csharp-overwrite-enum-naming) - A basic example on how to generate enum value names.
- [csharp-use-inheritance](./csharp-use-inheritance) - A basic example that shows how to introduce inheritance to classes
- [generate-javascript-models](./generate-javascript-models) - A basic example to generate JavaScript data models
- [javascript-use-esm](./javascript-use-esm) - A basic example that generate the models to use ESM module system.
Expand Down
17 changes: 17 additions & 0 deletions examples/csharp-overwrite-enum-naming/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# C# Generate custom enum value names

A basic example of how to custom enum value names.

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

exports[`Should be able to generate enums with custom value names and should log expected output to console 1`] = `
Array [
"public enum OrderStatus
{
Ordered,
UnderDelivery,
Deliveret,
Cancelled
}

public static class OrderStatusExtensions
{
public static dynamic GetValue(this OrderStatus enumValue)
{
switch (enumValue)
{
case OrderStatus.Ordered: return 30;
case OrderStatus.UnderDelivery: return 40;
case OrderStatus.Deliveret: return 50;
case OrderStatus.Cancelled: return 99;
}
return null;
}

public static OrderStatus? ToOrderStatus(dynamic value)
{
switch (value)
{
case 30: return OrderStatus.Ordered;
case 40: return OrderStatus.UnderDelivery;
case 50: return OrderStatus.Deliveret;
case 99: return OrderStatus.Cancelled;
}
return null;
}
}
",
]
`;
15 changes: 15 additions & 0 deletions examples/csharp-overwrite-enum-naming/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 generate enums with custom value names', () => {
afterAll(() => {
jest.restoreAllMocks();
});

test('and should log expected output to console', async () => {
await generate();
//Generate is called 2x, so even though we expect 1 model, we double it
expect(spy.mock.calls.length).toEqual(2);
expect(spy.mock.calls[1]).toMatchSnapshot();
});
});
48 changes: 48 additions & 0 deletions examples/csharp-overwrite-enum-naming/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { CSharpGenerator } from '../../src';

const generator = new CSharpGenerator({
presets: [
{
enum: {
item: ({model, item, content}) => {
// Lets see if an enum has any associated names
const hasCustomName = model.originalInput !== undefined && model.originalInput['x-enumNames'] !== undefined;
if (hasCustomName) {
// Lets see if the specific value has an associated name
const customName = model.originalInput['x-enumNames'][item];
if (customName !== undefined) {
return customName;
}
}
return content;
}
}
}
]
});

const jsonSchemaDraft7 = {
$schema: 'http://json-schema.org/draft-07/schema#',
title: 'OrderStatus',
type: 'number',
enum: [
30,
40,
50,
99
],
'x-enumNames': {
30: 'Ordered',
40: 'UnderDelivery',
50: 'Deliveret',
99: 'Cancelled'
}
};

export async function generate() : Promise<void> {
const models = await generator.generate(jsonSchemaDraft7);
for (const model of models) {
console.log(model.result);
}
}
generate();
10 changes: 10 additions & 0 deletions examples/csharp-overwrite-enum-naming/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/csharp-overwrite-enum-naming/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config" : {
"example_name" : "csharp-overwrite-enum-naming"
},
"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"
}
}