asyncapi / modelina

A library for generating typed models based on inputs such as AsyncAPI, OpenAPI, and JSON Schema documents with high customization
https://modelina.org
Apache License 2.0
313 stars 183 forks source link

Generate enum and use it for values. #188

Closed czlowiek488 closed 3 years ago

czlowiek488 commented 3 years ago

Context

I have a function saveProject which save a asyncApiMessage as a document to a database. This document is message wrapped in Envelope with additional properties. A message looks like this:

export interface MessageProjectCreated { //this is what is generated from generator-model-sdk everything else is my code
   eventName: "tms.event.project.created";
};
export const message: MessageProjectCreated = {
   eventName: "tms.event.project.created",
};

My document look like this:

export enum EventName {
  ProjectCreated = "tms.event.project.created",
  ...
};
export interface Envelope<T> {
   name: EventName;
   payload: T;
};

export const document: Envelope<MessageProjectCreated> = {
   name: message.eventName,
   payload: event,
};

Reason#1

My problem with this is that typescript treat generated "tms.event.project.created" as a string not as part of EventName. To make this work I had to replace Envelope with this.

export interface Envelope<T> {
   name: EventName | string; // a hacky way to make use of generated types
   payload: T;
};

Reason#2

I have to declare EventName enum by my own which can lead to unconsistency between event names from specification and enum written by me.

Description

I need a way to create enum in asyncapi and a way to specify field type as enum element. So something like this: (I modified json below from this answer in SO)

{
  "$id":"MessageProjectCreated",
  "properties": {
    "eventName": {
      "$ref": "http://example.com/some_schema.json#/definitions/EventName/tms.event.project.created"
    }
  }
}
{
  "$id": "http://example.com/some_schema.json",
  "definitions": {
    "EventName": {
      "enum": [ "tms.event.project.created"]
    }
  }
}

should generate something like this.

export enum EventName {
  ProjectCreated = "tms.event.project.created",
};
export interface MessageProjectCreated {
   eventName: EventName.ProjectCreated;
};
czlowiek488 commented 3 years ago

For now it is the most important feature for me. If you can please prioritize it.

jonaslagoni commented 3 years ago

Thanks for the feature request @czlowiek488

This is because the simplifier does not split enum models into separate models as the generator expects. I will add this feature as soon as the new simplifier is merged unless someone else has solved this.

asyncapi-bot commented 3 years ago

:tada: This issue has been resolved in version 0.10.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: