Skip to content

Commit

Permalink
Cleanup enum values, allow using identifier+value as an alternative t…
Browse files Browse the repository at this point in the history
…o @codegen_name (#2379) (#2380)
  • Loading branch information
swallez authored Jan 8, 2024
1 parent d75f194 commit 7aa6dbb
Show file tree
Hide file tree
Showing 75 changed files with 816 additions and 818 deletions.
7 changes: 6 additions & 1 deletion compiler/src/model/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,14 @@ export function modelEnumDeclaration (declaration: EnumDeclaration): model.Enum
.map(m => {
// names that contains `.` or `-` will be wrapped inside single quotes
const name = m.getName().replace(/'/g, '')
const member = {
const member: model.EnumMember = {
name: name
}
const value = m.getValue()
if (value != null && (typeof value === 'string')) {
member.name = value
member.codegenName = name
}
hoistEnumMemberAnnotations(member, m.getJsDocs())

return member
Expand Down
35 changes: 31 additions & 4 deletions docs/modeling-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,45 @@ property: Dictionary<string, string | long>

### Enum

Represents a set of allowed values:
Represents a set of allowed values.


```ts
enum MyEnum {
first = 0,
second = 1,
third = 2
first,
second,
third
}

property: MyEnum
```

Note that you don't have to provide both identifiers and values as is common in TypeScript. When there's only an identifier, the API specification compiler will use it for both the identifier and the value of enum members.

Also do not use identifiers and values for the sole purpose of providing upper-case identifiers (e.g. `FOO = 'foo'`). Each language generator will use the identifier casing that is expected by that language.

Some enumerations contain values that aren't identifiers, or that are not explicit enough. In that case you can either assign values to enum members or use the `@codegen_name` jsdoc tag to define the identifier that will be used by code generators:

```ts
enum MyEnum {
percent_of_sum,
mean,
/** @codegen_name z_score */
'z-score',
softmax
}

export enum IntervalUnit {
second = 's',
minute = 'm',
hour = 'h',
day = 'd',
week = 'w'
}
```

**Use custom identifiers for enum members sparingly**: we want to keep identifiers as close as possible to their value in JSON payloads to that usesr can easily map values found in the Elasticsearch reference documentation to code identifiers in the client libraries.

Some enumerations accept alternate values for some of their members. The `@aliases` jsdoc tac can be used to capture these values:

```ts
Expand Down
Loading

0 comments on commit 7aa6dbb

Please sign in to comment.