-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathx-enum-to-ms.js
92 lines (77 loc) · 2.41 KB
/
x-enum-to-ms.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* @copyright Copyright 2019 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
* @module "openapi-transformers/x-enum-to-ms.js"
*/
import { debuglog } from 'node:util';
import OpenApiTransformerBase from 'openapi-transformer-base';
const debug = debuglog('x-enum-to-ms');
function transformSchemaXEnumToXMsEnum(schema, schemaName) {
if ((!schema['x-enum-descriptions'] && !schema['x-enum-varnames'])
|| (schema['x-ms-enum'] && schema['x-ms-enum'].values)) {
// Schema doesn't have enum varnames/descriptions to convert,
// or already has x-ms-enum.values
return schema;
}
const {
'x-enum-descriptions': descriptions,
'x-enum-varnames': varnames,
...newSchema
} = schema;
const xMsEnum = {
// Make name first in output for aesthetics
name: undefined,
...newSchema['x-ms-enum'],
values: newSchema.enum.map((value, i) => ({
value,
description: descriptions ? descriptions[i] : undefined,
name: varnames ? varnames[i] : undefined,
})),
};
if (!xMsEnum.name) {
if (!schemaName) {
debug('Unable to determine required x-ms-enum.name for %O', schema);
return schema;
}
xMsEnum.name = schemaName;
}
newSchema['x-ms-enum'] = xMsEnum;
return newSchema;
}
/**
* Transformer to convert x-enum-descriptions and x-enum-varnames to x-ms-enum
* for Autorest.
*
* https://github.com/OpenAPITools/openapi-generator/blob/master/docs/templating.md#enum
* https://github.com/Azure/autorest/tree/master/docs/extensions#x-ms-enum
*/
export default class XEnumToXMsEnumTransformer extends OpenApiTransformerBase {
transformSchema(schema, schemaName) {
return transformSchemaXEnumToXMsEnum(
super.transformSchema(schema),
schemaName,
);
}
// Override to pass schemaName as second argument to transformSchema
transformMap(obj, transform) {
if (transform !== this.transformSchema) {
return super.transformMap(obj, transform);
}
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
return obj;
}
const newObj = { ...obj };
for (const [propName, propValue] of Object.entries(obj)) {
if (propValue !== undefined) {
newObj[propName] = transform.call(this, propValue, propName);
}
}
return newObj;
}
transformParameter(parameter) {
return transformSchemaXEnumToXMsEnum(
super.transformParameter(parameter),
undefined,
);
}
}