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: new accessor preset hook for C# class renderer #626

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
1 change: 1 addition & 0 deletions docs/presets.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ There are no additional methods.
|---|---|---|
| `ctor` | A method to extend rendered constructor for a given class. | - |
| `property` | A method to extend rendered given property. | `propertyName` as a name of a given property, `property` object as a [`CommonModel`](../src/models/CommonModel.ts) instance. |
| `accessor` | A method to extend rendered given property accessor. | `propertyName` as a name of a given property, `property` object as a [`CommonModel`](../src/models/CommonModel.ts) instance. |
| `setter` | A method to extend setter for a given property. | `propertyName` as a name of a given property, `property` object as a [`CommonModel`](../src/models/CommonModel.ts) instance. |
| `getter` | A method to extend getter for a given property. | `propertyName` as a name of a given property, `property` object as a [`CommonModel`](../src/models/CommonModel.ts) instance. |

Expand Down
10 changes: 7 additions & 3 deletions src/generators/csharp/CSharpPreset.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
/* eslint-disable @typescript-eslint/ban-types */
import { Preset, EnumPreset, ClassPreset } from '../../models';
import { Preset, EnumPreset, ClassPreset, PresetArgs, PropertyArgs } from '../../models';
import { ClassRenderer, CSHARP_DEFAULT_CLASS_PRESET } from './renderers/ClassRenderer';
import { CSHARP_DEFAULT_ENUM_PRESET, EnumRenderer } from './renderers/EnumRenderer';

// Our class preset uses custom `accessor` hook to craft getter and setters.
export interface CsharpClassPreset extends ClassPreset<ClassRenderer> {
accessor?: (args: PresetArgs<ClassRenderer, any> & PropertyArgs) => Promise<string> | string;
}

export type CSharpPreset = Preset<{
class: ClassPreset<ClassRenderer>;
class: CsharpClassPreset;
enum: EnumPreset<EnumRenderer>
}>;

Expand Down
39 changes: 22 additions & 17 deletions src/generators/csharp/renderers/ClassRenderer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CSharpRenderer } from '../CSharpRenderer';
import { ClassPreset, CommonModel, PropertyType } from '../../../models';
import { CommonModel, PropertyType } from '../../../models';
import { DefaultPropertyNames, getUniquePropertyName } from '../../../helpers';
import { pascalCase } from 'change-case';
import { CsharpClassPreset } from '../CSharpPreset';

/**
* Renderer for CSharp's `struct` type
Expand Down Expand Up @@ -53,35 +54,23 @@ ${this.indent(this.renderBlock(content, 2))}
return this.renderBlock(content);
}

async accessorFactory(property: CommonModel, propertyName: string, type: PropertyType): Promise<string> {
const formattedAccessorName = pascalCase(this.nameProperty(propertyName, property));
let propertyType = this.renderType(property);
if (type === PropertyType.additionalProperty || type === PropertyType.patternProperties) {
propertyType = `Dictionary<string, ${propertyType}>`;
}
return `public ${propertyType} ${formattedAccessorName}
{
${await this.runGetterPreset(propertyName, property, type)}
${await this.runSetterPreset(propertyName, property, type)}
}`;
}
async renderAccessors(): Promise<string> {
const properties = this.model.properties || {};
const content: string[] = [];

for (const [propertyName, property] of Object.entries(properties)) {
content.push(await this.accessorFactory(property, propertyName, PropertyType.property));
content.push(await this.runAccessorPreset(propertyName, property, PropertyType.property));
}

if (this.model.additionalProperties !== undefined) {
const propertyName = getUniquePropertyName(this.model, DefaultPropertyNames.additionalProperties);
content.push(await this.accessorFactory(this.model.additionalProperties, propertyName, PropertyType.additionalProperty));
content.push(await this.runAccessorPreset(propertyName, this.model.additionalProperties, PropertyType.additionalProperty));
}

if (this.model.patternProperties !== undefined) {
for (const [pattern, patternModel] of Object.entries(this.model.patternProperties)) {
const propertyName = getUniquePropertyName(this.model, `${pattern}${DefaultPropertyNames.patternProperties}`);
content.push(await this.accessorFactory(patternModel, propertyName, PropertyType.patternProperties));
content.push(await this.runAccessorPreset(propertyName, patternModel, PropertyType.patternProperties));
}
}

Expand All @@ -92,6 +81,10 @@ ${this.indent(this.renderBlock(content, 2))}
return this.runPreset('ctor');
}

runAccessorPreset(propertyName: string, property: CommonModel, type: PropertyType = PropertyType.property): Promise<string> {
return this.runPreset('accessor', { propertyName, property, type});
}

runPropertyPreset(propertyName: string, property: CommonModel, type: PropertyType = PropertyType.property): Promise<string> {
return this.runPreset('property', { propertyName, property, type});
}
Expand All @@ -105,7 +98,7 @@ ${this.indent(this.renderBlock(content, 2))}
}
}

export const CSHARP_DEFAULT_CLASS_PRESET: ClassPreset<ClassRenderer> = {
export const CSHARP_DEFAULT_CLASS_PRESET: CsharpClassPreset = {
self({ renderer }) {
return renderer.defaultSelf();
},
Expand All @@ -117,6 +110,18 @@ export const CSHARP_DEFAULT_CLASS_PRESET: ClassPreset<ClassRenderer> = {
}
return `private ${propertyType} ${propertyName};`;
},
async accessor({ renderer, propertyName, property, type }) {
const formattedAccessorName = pascalCase(renderer.nameProperty(propertyName, property));
let propertyType = renderer.renderType(property);
if (type === PropertyType.additionalProperty || type === PropertyType.patternProperties) {
propertyType = `Dictionary<string, ${propertyType}>`;
}
return `public ${propertyType} ${formattedAccessorName}
{
${await renderer.runGetterPreset(propertyName, property, type)}
${await renderer.runSetterPreset(propertyName, property, type)}
}`;
},
getter({ renderer, propertyName, property }) {
const formattedPropertyName = renderer.nameProperty(propertyName, property);
return `get { return ${formattedPropertyName}; }`;
Expand Down
89 changes: 50 additions & 39 deletions test/generators/csharp/CSharpGenerator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,36 +63,6 @@ describe('CSharpGenerator', () => {
expect(classModel.dependencies).toEqual(['using System.Collections.Generic;']);
});

test('should work custom preset for `class` type', async () => {
const doc = {
$id: 'CustomClass',
type: 'object',
properties: {
property: { type: 'string' },
},
additionalProperties: {
type: 'string'
}
};

generator = new CSharpGenerator({ presets: [
{
class: {
property({ propertyName, property, renderer }) {
return `private ${propertyName} ${renderer.renderType(property)}`;
},
}
}
] });

const inputModel = await generator.process(doc);
const model = inputModel.models['CustomClass'];

const classModel = await generator.render(model, inputModel);
expect(classModel.result).toMatchSnapshot();
expect(classModel.dependencies).toEqual(['using System.Collections.Generic;']);
});

test.each([
{
name: 'with enums sharing same type',
Expand Down Expand Up @@ -148,15 +118,7 @@ describe('CSharpGenerator', () => {
enum: ['test+', 'test', 'test-', 'test?!', '*test']
};

generator = new CSharpGenerator({ presets: [
{
enum: {
self({ content }) {
return content;
},
}
}
]});
generator = new CSharpGenerator();

const inputModel = await generator.process(doc);
const model = inputModel.models['States'];
Expand Down Expand Up @@ -222,4 +184,53 @@ describe('CSharpGenerator', () => {
const expectedError = new Error('You cannot use reserved CSharp keyword (true) as namespace, please use another.');
await expect(generator.generateCompleteModels(doc, config)).rejects.toEqual(expectedError);
});

describe('class renderer', () => {
const doc = {
$id: 'CustomClass',
type: 'object',
properties: {
property: { type: 'string' },
},
additionalProperties: {
type: 'string'
}
};

test('should be able to overwrite accessor preset hook', async () => {
generator = new CSharpGenerator({ presets: [
{
class: {
accessor() {
return 'my own custom factory';
}
}
}
] });

const inputModel = await generator.process(doc);
const model = inputModel.models['CustomClass'];

const classModel = await generator.render(model, inputModel);
expect(classModel.result).toMatchSnapshot();
});

test('should be able to overwrite property preset hook', async () => {
generator = new CSharpGenerator({ presets: [
{
class: {
property() {
return 'my own property';
},
}
}
] });

const inputModel = await generator.process(doc);
const model = inputModel.models['CustomClass'];

const classModel = await generator.render(model, inputModel);
expect(classModel.result).toMatchSnapshot();
});
});
});
49 changes: 30 additions & 19 deletions test/generators/csharp/__snapshots__/CSharpGenerator.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`CSharpGenerator class renderer should be able to overwrite accessor preset hook 1`] = `
"public class CustomClass {
private string property;
private Dictionary<string, string> additionalProperties;

my own custom factory

my own custom factory
}"
`;

exports[`CSharpGenerator class renderer should be able to overwrite property preset hook 1`] = `
"public class CustomClass {
my own property
my own property

public string Property
{
get { return property; }
set { property = value; }
}

public Dictionary<string, string> AdditionalProperties
{
get { return additionalProperties; }
set { additionalProperties = value; }
}
}"
`;

exports[`CSharpGenerator should not render reserved keyword 1`] = `
"public class Address {
private string reservedReservedEnum;
Expand Down Expand Up @@ -492,25 +522,6 @@ exports[`CSharpGenerator should render models and their dependencies 2`] = `
}"
`;

exports[`CSharpGenerator should work custom preset for \`class\` type 1`] = `
"public class CustomClass {
private property string
private additionalProperties string

public string Property
{
get { return property; }
set { property = value; }
}

public Dictionary<string, string> AdditionalProperties
{
get { return additionalProperties; }
set { additionalProperties = value; }
}
}"
`;

exports[`CSharpGenerator should work custom preset for \`enum\` type 1`] = `
"public enum CustomEnum {
Texas, Alabama, California
Expand Down