Skip to content

Commit d56c059

Browse files
authored
CodableWithConfiguration support (#8)
1 parent 8e1c7c0 commit d56c059

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

Sources/Decoder/URLQueryDecoder.swift

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public final class URLQueryDecoder: Sendable {
5151
}
5252

5353
public func decode<T: Decodable>(
54-
_ type: T.Type,
54+
_ type: T.Type = T.self,
5555
from query: String
5656
) throws -> T {
5757
let options = optionsMutex.withLock { $0 }
@@ -68,4 +68,25 @@ public final class URLQueryDecoder: Sendable {
6868

6969
return try T(from: decoder)
7070
}
71+
72+
@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
73+
public func decode<T: DecodableWithConfiguration>(
74+
_ type: T.Type = T.self,
75+
from query: String,
76+
configuration: T.DecodingConfiguration
77+
) throws -> T {
78+
let options = optionsMutex.withLock { $0 }
79+
80+
let deserializer = URLQueryDeserializer()
81+
let value = try deserializer.deserialize(query)
82+
83+
let decoder = URLQuerySingleValueDecodingContainer(
84+
value: value,
85+
options: options,
86+
userInfo: userInfo,
87+
codingPath: []
88+
)
89+
90+
return try T(from: decoder, configuration: configuration)
91+
}
7192
}

Sources/Encoder/URLQueryEncoder.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,36 @@ public final class URLQueryEncoder: Sendable {
9898

9999
return serializer.serialize(urlEncodedForm)
100100
}
101+
102+
@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
103+
public func encode<T: EncodableWithConfiguration>(
104+
_ value: T,
105+
configuration: T.EncodingConfiguration
106+
) throws -> String {
107+
let options = optionsMutex.withLock { $0 }
108+
109+
let encoder = URLQuerySingleValueEncodingContainer(
110+
options: options,
111+
userInfo: userInfo,
112+
codingPath: []
113+
)
114+
115+
try value.encode(to: encoder, configuration: configuration)
116+
117+
guard case let .dictionary(urlEncodedForm) = encoder.resolveValue() else {
118+
let errorContext = EncodingError.Context(
119+
codingPath: [],
120+
debugDescription: "Root component cannot be encoded in URL"
121+
)
122+
123+
throw EncodingError.invalidValue(value, errorContext)
124+
}
125+
126+
let serializer = URLQuerySerializer(
127+
arrayEncodingStrategy: arrayEncodingStrategy,
128+
spaceEncodingStrategy: spaceEncodingStrategy
129+
)
130+
131+
return serializer.serialize(urlEncodedForm)
132+
}
101133
}

0 commit comments

Comments
 (0)