Skip to content

Commit

Permalink
feat(mock): infer type from enum values for string and number (orval-…
Browse files Browse the repository at this point in the history
…labs#1491)

* feat(mock): infer type from enum values for string and number

* cleanup
  • Loading branch information
lnkarma authored Jun 30, 2024
1 parent 1788bd5 commit 833faeb
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/mock/src/faker/getters/scalar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ export const getMockScalar = ({
};
}

switch (item.type) {
const type = getItemType(item);

switch (type) {
case 'number':
case 'integer': {
let value = getNullable(
Expand Down Expand Up @@ -303,3 +305,15 @@ export const getMockScalar = ({
}
}
};

function getItemType(item: MockSchemaObject) {
if (item.type) return item.type;
if (!item.enum) return;

const uniqTypes = new Set(item.enum.map((value) => typeof value));
if (uniqTypes.size > 1) return;

const type = Array.from(uniqTypes.values()).at(0);
if (!type) return;
return ['string', 'number'].includes(type) ? type : undefined;
}
8 changes: 8 additions & 0 deletions tests/configs/mock.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,12 @@ export default defineConfig({
target: '../specifications/enum-refs.yaml',
},
},
typelessEnum: {
input: '../specifications/typelessEnum.yaml',
output: {
schemas: '../generated/mock/typelessEnum/schemas',
target: '../generated/mock/typelessEnum',
mock: true,
},
},
});
29 changes: 29 additions & 0 deletions tests/specifications/typelessEnum.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
openapi: 3.0.3
info:
title: Typeless enums
version: 1.0.0
paths:
/api/colors:
get:
summary: sample colors
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/ColorObject'
components:
schemas:
Colors1:
type: string
enum: [red, blue, yellow]
Colors2:
enum: [green, purple, orange]
ColorObject:
type: object
properties:
color:
oneOf:
- $ref: '#/components/schemas/Colors1'
- $ref: '#/components/schemas/Colors2'

0 comments on commit 833faeb

Please sign in to comment.