Skip to content

Commit f250493

Browse files
committed
Make sure that the type discriminator is the first property
1 parent 5615a46 commit f250493

File tree

3 files changed

+139334
-139313
lines changed

3 files changed

+139334
-139313
lines changed

compiler/src/compiler.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,13 @@ export default class Compiler {
6262
this.model = await step(this.model, this.jsonSpec, this.errors)
6363
}
6464

65+
// We manually sort the object keys => disable sort
66+
const nonDeterministicStringify = stringify.configure({ deterministic: false })
67+
6568
await mkdir(join(this.outputFolder, 'schema'), { recursive: true })
6669
await writeFile(
6770
join(this.outputFolder, 'schema', 'schema.json'),
68-
stringify(this.model, null, 2),
71+
nonDeterministicStringify(this.model, null, 2),
6972
'utf8'
7073
)
7174

compiler/src/model/build-model.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,9 @@ export function compileSpecification (endpointMappings: Record<string, model.End
156156
model.types.push(modelTypeAlias(declaration))
157157
}
158158

159+
// Sort object keys in alphabetical order and ensure that the discriminator key always comes first
160+
model.types = model.types.map(x => sortObjectKeys(x, 'kind'))
161+
159162
// Sort the types in alphabetical order
160163
sortTypeDefinitions(model.types)
161164

@@ -585,3 +588,18 @@ function visitRequestOrResponseProperty (member: PropertyDeclaration | PropertyS
585588

586589
return { name, properties, valueOf }
587590
}
591+
592+
function sortObjectKeys (type: any, discriminator: string): any {
593+
const keys = Object.keys(type).sort((a, b) => a.localeCompare(b))
594+
595+
const result = {}
596+
597+
result[discriminator] = type[discriminator]
598+
keys.forEach(key => {
599+
if (key !== discriminator){
600+
result[key] = type[key]
601+
}
602+
})
603+
604+
return result
605+
}

0 commit comments

Comments
 (0)