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: add support to display examples #53

Merged
merged 3 commits into from
Aug 16, 2021
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,16 @@ channels:
await parser.parse(asyncapiWithAvro)
```

## Features

### Support for extra attributes on top of Avro specification

Additional attributes not defined in the [Avro Specification](https://avro.apache.org/docs/current/spec.html) are permitted and are treated as a metadata by the specification. To improve human readability of generated AsyncAPI documentation and to leverage more features from the JSON schema we included support for the extra attributes that can be added into Avro document.

#### List of all supported extra attributes

- `example` - Can be used to define the example value from the business domain of given field. Value will be propagated into [examples attribute](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.5) of JSON schema and therefore will be picked for the generated "Example of payload" when using some AsyncAPI documentation generator.

## Limitations

### Float and double-precision numbers
Expand Down
4 changes: 2 additions & 2 deletions tests/parse.test.js

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

4 changes: 2 additions & 2 deletions tests/schemas/Person-1.8.2.avsc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "Person",
"type": "record",
"fields": [
{"name": "name", "type": "string"},
{"name": "name", "type": "string", example: "Donkey"},
{"name": "age", "type": ["null", "int"], "default": null},
{
"name": "favoriteProgrammingLanguage",
Expand All @@ -13,7 +13,7 @@
"type": {
"name": "Address",
"type": "record",
"fields": [{"name": "zipcode", "type": "int"}]
"fields": [{"name": "zipcode", "type": "int", example: "53003"}]
}
}
]
Expand Down
6 changes: 3 additions & 3 deletions tests/schemas/Person-1.9.0.avsc
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"name": "Person",
"type": "record",
"fields": [
{"name": "name", "type": "string"},
{"name": "age", "type": ["null", "int"], "default": null},
{"name": "name", "type": "string", example: "Donkey"},
{"name": "age", "type": ["null", "int"], "default": null, example: "123"},
{
"name": "favoriteProgrammingLanguage",
"type": {"name": "ProgrammingLanguage", "type": "enum", "symbols": ["JS", "Java", "Go", "Rust", "C"], "default": "JS"}
Expand All @@ -13,7 +13,7 @@
"type": {
"name": "Address",
"type": "record",
"fields": [{"name": "zipcode", "type": "int"}]
"fields": [{"name": "zipcode", "type": "int", example: "53003"}]
}
},
{"name": "someid", "type": "uuid"}
Expand Down
2 changes: 1 addition & 1 deletion tests/to-json-schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe('avroToJsonSchema()', function () {

it('transforms union values', async function () {
const result = await avroToJsonSchema(['null', 'int']);
expect(result).toEqual({ oneOf: [{ type: 'null' }, { type: 'integer', minimum: INT_MIN, maximum: INT_MAX }] });
expect(result).toEqual({ oneOf: [{ type: 'integer', minimum: INT_MIN, maximum: INT_MAX }, { type: 'null' }] });
});

it('transforms map values', async function () {
Expand Down
52 changes: 45 additions & 7 deletions to-json-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,61 @@ const typeMappings = {
uuid: 'string',
};

const commonAttributesMapping = (avroDefinition, jsonSchema) => {
if (avroDefinition.doc) jsonSchema.description = avroDefinition.doc;
if (avroDefinition.default !== undefined) jsonSchema.default = avroDefinition.default;
};

const exampleAttributeMapping = (typeInput, example, jsonSchemaInput) => {
let type = typeInput;
let jsonSchema = jsonSchemaInput;

// Map example to first non-null type
if (Array.isArray(typeInput) && typeInput.length > 0) {
const pickSecondType = typeInput.length > 1 && typeInput[0] === 'null';
type = typeInput[+pickSecondType];
jsonSchema = jsonSchema.oneOf[0];
}

if (example === undefined || jsonSchema.examples || Array.isArray(type)) return;

switch (type) {
case 'boolean':
jsonSchema.examples = [example === 'true'];
break;
case 'int':
jsonSchema.examples = [parseInt(example, 10)];
break;
default:
jsonSchema.examples = [example];
}
};

module.exports.avroToJsonSchema = async function avroToJsonSchema(avroDefinition) {
const jsonSchema = {};
const isUnion = Array.isArray(avroDefinition);

if (isUnion) {
jsonSchema.oneOf = [];
let nullDef = null;
for (const avroDef of avroDefinition) {
const def = await avroToJsonSchema(avroDef);
jsonSchema.oneOf.push(def);
// avroDef can be { type: 'int', default: 1 } and this is why avroDef.type has priority here
const defType = avroDef.type || avroDef;
ITman1 marked this conversation as resolved.
Show resolved Hide resolved
// To prefer non-null values in the examples skip null definition here and push it as the last element after loop
if (defType === 'null') nullDef = def; else jsonSchema.oneOf.push(def);
}

if (nullDef) jsonSchema.oneOf.push(nullDef);

return jsonSchema;
}

// Avro definition can be a string (e.g. "int")
// or an object like { type: "int" }
const type = avroDefinition.type || avroDefinition;
jsonSchema.type = typeMappings[type];

switch (type) {
case 'int':
jsonSchema.minimum = INT_MIN;
Expand Down Expand Up @@ -70,16 +106,18 @@ module.exports.avroToJsonSchema = async function avroToJsonSchema(avroDefinition
const propsMap = new Map();
for (const field of avroDefinition.fields) {
const def = await avroToJsonSchema(field.type);
if (field.doc) def.description = field.doc;
if (field.default) def.default = field.default;

commonAttributesMapping(field, def);
exampleAttributeMapping(field.type, field.example, def);

propsMap.set(field.name, def);
}
jsonSchema.properties = Object.fromEntries(propsMap.entries());
break;
}

if (avroDefinition.doc) jsonSchema.description = avroDefinition.doc;
if (avroDefinition.default !== undefined) jsonSchema.default = avroDefinition.default;
commonAttributesMapping(avroDefinition, jsonSchema);
exampleAttributeMapping(type, avroDefinition.example, jsonSchema);

return jsonSchema;
};