|
| 1 | +import { Enum } from './client/interfaces/Enum'; |
| 2 | +import { Model } from './client/interfaces/Model'; |
| 3 | +import { OperationResponse } from './client/interfaces/OperationResponse'; |
| 4 | +import { Service } from './client/interfaces/Service'; |
| 5 | + |
| 6 | +export enum Case { |
| 7 | + NONE = 'none', |
| 8 | + CAMEL = 'camel', |
| 9 | + SNAKE = 'snake', |
| 10 | +} |
| 11 | +// Convert a string from snake case to camel case. |
| 12 | +const toCamelCase = (str: string): string => { |
| 13 | + return str.replace(/_([a-z0-9])/g, match => match[1].toUpperCase()); |
| 14 | +}; |
| 15 | + |
| 16 | +// Convert a string from camel case or pascal case to snake case. |
| 17 | +const toSnakeCase = (str: string): string => { |
| 18 | + return str.replace(/([A-Z])/g, match => `_${match.toLowerCase()}`); |
| 19 | +}; |
| 20 | + |
| 21 | +const transforms = { |
| 22 | + [Case.CAMEL]: toCamelCase, |
| 23 | + [Case.SNAKE]: toSnakeCase, |
| 24 | +}; |
| 25 | + |
| 26 | +// A recursive function that looks at the models and their properties and |
| 27 | +// converts each property name using the provided transform function. |
| 28 | +export const convertModelCase = <T extends Model | OperationResponse>(model: T, type: Exclude<Case, Case.NONE>): T => { |
| 29 | + return { |
| 30 | + ...model, |
| 31 | + name: transforms[type](model.name), |
| 32 | + link: model.link ? convertModelCase(model.link, type) : null, |
| 33 | + enum: model.enum.map(modelEnum => convertEnumCase(modelEnum, type)), |
| 34 | + enums: model.enums.map(property => convertModelCase(property, type)), |
| 35 | + properties: model.properties.map(property => convertModelCase(property, type)), |
| 36 | + }; |
| 37 | +}; |
| 38 | + |
| 39 | +const convertEnumCase = (modelEnum: Enum, type: Exclude<Case, Case.NONE>): Enum => { |
| 40 | + return { |
| 41 | + ...modelEnum, |
| 42 | + name: transforms[type](modelEnum.name), |
| 43 | + }; |
| 44 | +}; |
| 45 | + |
| 46 | +export const convertServiceCase = (service: Service, type: Exclude<Case, Case.NONE>): Service => { |
| 47 | + return { |
| 48 | + ...service, |
| 49 | + operations: service.operations.map(op => ({ |
| 50 | + ...op, |
| 51 | + parameters: op.parameters.map(opParameter => convertModelCase(opParameter, type)), |
| 52 | + results: op.results.map(results => convertModelCase(results, type)), |
| 53 | + })), |
| 54 | + }; |
| 55 | +}; |
0 commit comments