Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(msw): simplify combine #1815

Merged
merged 4 commits into from
Feb 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 65 additions & 124 deletions packages/mock/src/faker/getters/combine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,144 +66,85 @@ export const combineSchemasMock = ({

includedProperties.push(...(itemResolvedValue?.includedProperties ?? []));
combineImports.push(...(itemResolvedValue?.imports ?? []));
let containsOnlyPrimitiveValues = true;

const value = (item[separator] ?? []).reduce((acc, val, index, arr) => {
if (
'$ref' in val &&
existingReferencedProperties.includes(pascal(val.$ref.split('/').pop()!))
) {
if (arr.length === 1) {
return 'undefined';
}

return acc;
}

// the required fields in this schema need to be considered
// in the sub schema under the allOf key
if (separator === 'allOf' && item.required) {
if (isSchema(val) && val.required) {
val = { ...val, required: [...item.required, ...val.required] };
} else {
val = { ...val, required: item.required };
}
}

const resolvedValue = resolveMockValue({
schema: {
...val,
name: item.name,
path: item.path ? item.path : '#',
},
combine: {
separator,
includedProperties:
separator !== 'oneOf'
? includedProperties
: itemResolvedValue?.includedProperties ?? [],
},
mockOptions,
operationId,
tags,
context,
imports,
existingReferencedProperties,
splitMockImplementations,
});

combineImports.push(...resolvedValue.imports);
includedProperties.push(...(resolvedValue.includedProperties ?? []));

const isLastElement = index === arr.length - 1;

let currentValue = resolvedValue.value;

if (itemResolvedValue?.value && separator === 'oneOf') {
const splitValues = resolvedValue.value.split('},{');
const joined = splitValues.join(`,${itemResolvedValue.value}},{`);
currentValue = `${joined.slice(0, -1)},${itemResolvedValue.value}}`;
}

if (itemResolvedValue?.value && separator !== 'oneOf' && isLastElement) {
currentValue = `${currentValue ? `${currentValue},` : ''}${itemResolvedValue.value}`;
}

if (
resolvedValue.type === undefined &&
currentValue &&
separator === 'allOf'
) {
currentValue = `...${currentValue}`;
}

const isObjectBounds =
!combine ||
(['oneOf', 'anyOf'].includes(combine.separator) && separator === 'allOf');

if (!index && isObjectBounds) {
const value = (item[separator] ?? []).reduce(
(acc, val, _, arr) => {
if (
resolvedValue.enums ||
separator === 'oneOf' ||
separator === 'anyOf' ||
resolvedValue.type === 'array'
'$ref' in val &&
existingReferencedProperties.includes(
pascal(val.$ref.split('/').pop()!),
)
) {
if (arr.length === 1) {
return `faker.helpers.arrayElement([${currentValue}])`;
return 'undefined';
}
return `faker.helpers.arrayElement([${currentValue},`;
}

if (arr.length === 1) {
if (resolvedValue.type && resolvedValue.type !== 'object') {
return currentValue;
}
return `{${currentValue}}`;
}

if (currentValue) {
return `{${currentValue},`;
}
return '{';
}

if (isLastElement) {
if (
resolvedValue.enums ||
separator === 'oneOf' ||
separator === 'anyOf' ||
resolvedValue.type === 'array'
) {
return `${acc}${currentValue}${!combine ? '])' : ''}`;
return acc;
}

if (currentValue === '{}') {
currentValue = '';

if (acc.toString().endsWith(',')) {
acc = acc.toString().slice(0, -1);
// the required fields in this schema need to be considered
// in the sub schema under the allOf key
if (separator === 'allOf' && item.required) {
if (isSchema(val) && val.required) {
val = { ...val, required: [...item.required, ...val.required] };
} else {
val = { ...val, required: item.required };
}
}

return `${acc}${currentValue}${isObjectBounds ? '}' : ''}`;
}

if (currentValue === '{}') {
currentValue = '';

if (acc.toString().endsWith(',')) {
acc = acc.toString().slice(0, -1);
const resolvedValue = resolveMockValue({
schema: {
...val,
name: item.name,
path: item.path ? item.path : '#',
},
combine: {
separator,
includedProperties:
separator !== 'oneOf'
? includedProperties
: itemResolvedValue?.includedProperties ?? [],
},
mockOptions,
operationId,
tags,
context,
imports,
existingReferencedProperties,
splitMockImplementations,
});

combineImports.push(...resolvedValue.imports);
includedProperties.push(...(resolvedValue.includedProperties ?? []));

if (resolvedValue.value === '{}') {
containsOnlyPrimitiveValues = false;
return acc;
}
}

if (!currentValue) {
return acc;
}

return `${acc}${currentValue},`;
}, '');
if (resolvedValue.value.startsWith('{')) {
containsOnlyPrimitiveValues = false;
return `${acc}${separator === 'allOf' ? '...' : ''}${resolvedValue.value},`;
} else if (resolvedValue.type === 'object') {
containsOnlyPrimitiveValues = false;
}
return `${acc}${resolvedValue.value},`;
},
`${separator === 'allOf' ? '' : 'faker.helpers.arrayElement(['}`,
);
let finalValue =
value === 'undefined'
? value
: `${combine ? '...' : ''}${separator === 'allOf' && !containsOnlyPrimitiveValues ? '{' : ''}${value}${separator === 'allOf' ? (containsOnlyPrimitiveValues ? '' : '}') : '])'}`;
if (itemResolvedValue) {
finalValue = `{${finalValue.startsWith('...') ? '' : '...'}${finalValue}, ${itemResolvedValue.value}}`;
}
if (finalValue.endsWith(',')) {
finalValue = finalValue.substring(0, finalValue.length - 1);
}

return {
value: value,
value: finalValue,
imports: combineImports,
name: item.name,
includedProperties,
Expand Down
5 changes: 1 addition & 4 deletions packages/mock/src/faker/resolvers/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,7 @@ export const resolveMockValue = ({
}

const args = `${overrideVarName}: ${type} = {}`;
const value = newSchema.oneOf
? `faker.helpers.arrayElement([${scalar.value}])`
: scalar.value;
const func = `export const ${funcName} = (${args}): ${newSchema.name} => ({...${value}, ...${overrideVarName}});`;
const func = `export const ${funcName} = (${args}): ${newSchema.name} => ({${scalar.value.startsWith('...') ? '' : '...'}${scalar.value}, ...${overrideVarName}});`;
splitMockImplementations?.push(func);
}

Expand Down
48 changes: 48 additions & 0 deletions tests/configs/default.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,46 @@ export default defineConfig({
target: '../generated/default/default-status/endpoints.ts',
},
},
'all-of-one-of': {
input: '../specifications/all-of-one-of.yaml',
output: {
schemas: '../generated/default/all-of-one-of/model',
target: '../generated/default/all-of-one-of/endpoints.ts',
mock: true,
},
},
'all-of-primitive': {
input: '../specifications/all-of-primitive.yaml',
output: {
schemas: '../generated/default/all-of-primitive/model',
target: '../generated/default/all-of-primitive/endpoints.ts',
mock: true,
},
},
'one-of': {
input: '../specifications/one-of.yaml',
output: {
schemas: '../generated/default/one-of/model',
target: '../generated/default/one-of/endpoints.ts',
mock: true,
},
},
'one-of-primitive': {
input: '../specifications/one-of-primitive.yaml',
output: {
schemas: '../generated/default/one-of-primitive/model',
target: '../generated/default/one-of-primitive/endpoints.ts',
mock: true,
},
},
'any-of-primitive': {
input: '../specifications/any-of-primitive.yaml',
output: {
schemas: '../generated/default/any-of-primitive/model',
target: '../generated/default/any-of-primitive/endpoints.ts',
mock: true,
},
},
'circular-v2': {
input: '../specifications/circular-v2.yaml',
output: {
Expand All @@ -124,6 +164,14 @@ export default defineConfig({
mock: true,
},
},
'all-of-ref': {
input: '../specifications/all-of-ref.yaml',
output: {
schemas: '../generated/default/all-of-ref/model',
target: '../generated/default/all-of-ref/endpoints.ts',
mock: true,
},
},
'deeply-nested-refs': {
input: '../specifications/deeply-nested-refs.yaml',
output: {
Expand Down
38 changes: 38 additions & 0 deletions tests/specifications/all-of-one-of.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
openapi: 3.0.1
info:
version: 1.0.0
title: any-of-one-of
paths:
/something:
post:
responses:
'200':
description: Something
content:
application/json:
schema:
type: object
properties:
uploads:
type: array
items:
allOf:
- type: object
properties:
file_type:
type: string
- oneOf:
- type: object
properties:
type:
type: string
enum:
- a
- type: object
properties:
type:
type: string
enum:
- b
other:
type: string
32 changes: 32 additions & 0 deletions tests/specifications/all-of-primitive.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
openapi: 3.0.1
info:
title: All Of Primitive
version: v1.0
paths:
/pets:
get:
operationId: get-pets
responses:
'200':
content:
application/json:
schema:
items:
$ref: '#/components/schemas/Pets'
type: array
description: OK
components:
schemas:
Pets:
properties:
petId:
allOf:
- $ref: '#/components/schemas/DogId'
- $ref: '#/components/schemas/CatId'
nullable: true
DogId:
nullable: true
type: string
CatId:
description: test
type: string
32 changes: 32 additions & 0 deletions tests/specifications/all-of-ref.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
openapi: 3.0.3
info:
title: All Of Ref
version: 1.0.0
paths:
/pet:
get:
operationId: get-pet
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: OK
tags:
- Pet
components:
schemas:
Pet:
type: object
required:
- id
- detail
properties:
id:
type: string
detail:
allOf:
- $ref: '#/components/schemas/Name'
Name:
type: string
Loading
Loading