Skip to content

Commit 36253d3

Browse files
Merge pull request #1024 from nartc/enum-name
docs(swagger): add docs for enumName
2 parents 12ff6da + de19946 commit 36253d3

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

content/recipes/swagger.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,80 @@ With `isArray` set to **true**, the `enum` can be selected as a **multi-select**
158158

159159
<figure><img src="/assets/enum_query_array.gif" /></figure>
160160

161+
#### Enums schema
162+
163+
By default, the `enum` property will add a raw definition of [Enum](https://swagger.io/docs/specification/data-models/enums/) on the `parameter`.
164+
165+
```yaml
166+
CatDetail:
167+
type: 'object'
168+
properties:
169+
...
170+
- breed:
171+
type: 'string'
172+
enum:
173+
- Persian
174+
- Tabby
175+
- Siamese
176+
```
177+
178+
The above specification works fine for most cases. However, if you are utilizing a tool that takes the specification as **input** and generates **client-side** code, you might run into a problem with the generated code containing duplicated `enums`. Consider the following code snippet:
179+
180+
```typescript
181+
// generated client-side code
182+
export class CatDetail {
183+
breed: CatDetailEnum;
184+
}
185+
186+
export class CatInformation {
187+
breed: CatInformationEnum;
188+
}
189+
190+
export enum CatDetailEnum {
191+
Persian = 'Persian',
192+
Tabby = 'Tabby',
193+
Siamese = 'Siamese'
194+
}
195+
196+
export enum CatInformationEnum {
197+
Persian = 'Persian',
198+
Tabby = 'Tabby',
199+
Siamese = 'Siamese'
200+
}
201+
```
202+
203+
> info **Hint** The above snippet is generated using a tool called [NSwag](https://github.com/RicoSuter/NSwag).
204+
205+
You can see that now you have two `enums` that are exactly the same.
206+
To address this issue, you can pass an `enumName` next to `enum` property in your decorator.
207+
208+
```typescript
209+
export class CatDetail {
210+
@ApiProperty({ enum: CatBreed, enumName: 'CatBreed' })
211+
breed: CatBreed;
212+
}
213+
```
214+
215+
`enumName` enables `nestjs/swagger` to turn `CatBreed` into its own `schema` which in turns makes `CatBreed` reusable. The specification will look like the following:
216+
217+
```yaml
218+
CatDetail:
219+
type: 'object'
220+
properties:
221+
...
222+
- breed:
223+
schema:
224+
$ref: '#/components/schemas/CatBreed'
225+
CatBreed:
226+
type: string
227+
enum:
228+
- Persian
229+
- Tabby
230+
- Siamese
231+
```
232+
233+
> info **Hint** Any **decorator** that takes `enum` as a property will also take `enumName`.
234+
161235
#### Arrays
162236

163237
When the property is an array, we must manually indicate the array type as shown below:

0 commit comments

Comments
 (0)