Skip to content

Commit 68ef99c

Browse files
author
simonbility
committed
Allow substituting types
1 parent 28a4629 commit 68ef99c

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateSchema.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,21 @@ extension TypesFileTranslator {
8787
)
8888
)
8989
}
90+
if let substituteTypeName = schema.vendorExtensions["x-swift-open-api-substitute-type"]?.value
91+
as? String
92+
{
93+
try diagnostics.emit(.note(message: "Substituting type \(typeName) with \(substituteTypeName)"))
94+
let substitutedType = TypeName(swiftKeyPath: substituteTypeName.components(separatedBy: ".")).asUsage
95+
96+
let typealiasDecl = try translateTypealias(
97+
named: typeName,
98+
userDescription: overrides.userDescription ?? schema.description,
99+
to: substitutedType.withOptional(
100+
overrides.isOptional ?? typeMatcher.isOptional(schema, components: components)
101+
)
102+
)
103+
return [typealiasDecl]
104+
}
90105

91106
// If this type maps to a referenceable schema, define a typealias
92107
if let builtinType = try typeMatcher.tryMatchReferenceableType(for: schema, components: components) {

Tests/OpenAPIGeneratorCoreTests/Translator/TypesTranslator/Test_translateSchemas.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,30 @@ class Test_translateSchemas: Test_Core {
4747
XCTAssertEqual(collector.diagnostics.map(\.description), diagnosticDescriptions)
4848
}
4949
}
50+
51+
func testSchemaTypeSubstitution() throws {
52+
let typeName = TypeName(swiftKeyPath: ["Foo"])
53+
54+
let schema = try loadSchemaFromYAML(
55+
#"""
56+
type: string
57+
x-swift-open-api-substitute-type: MyLibrary.MyCustomType
58+
"""#
59+
)
60+
let collector = AccumulatingDiagnosticCollector()
61+
let translator = makeTranslator(diagnostics: collector)
62+
let translated = try translator.translateSchema(typeName: typeName, schema: schema, overrides: .none)
63+
64+
XCTAssertEqual(
65+
collector.diagnostics.map(\.description),
66+
["note: Substituting type Foo with MyLibrary.MyCustomType"]
67+
)
68+
XCTAssertTrue(translated.count == 1, "Should have one translated schema")
69+
guard case let .typealias(typeAliasDescription) = translated.first?.strippingTopComment else {
70+
XCTFail("Expected typealias description got")
71+
return
72+
}
73+
XCTAssertEqual(typeAliasDescription.name, "Foo")
74+
XCTAssertEqual(typeAliasDescription.existingType, .member(["MyLibrary", "MyCustomType"]))
75+
}
5076
}

0 commit comments

Comments
 (0)