diff --git a/Sources/Decoder/URLQueryDecoder.swift b/Sources/Decoder/URLQueryDecoder.swift index 280235a..05040ec 100644 --- a/Sources/Decoder/URLQueryDecoder.swift +++ b/Sources/Decoder/URLQueryDecoder.swift @@ -51,7 +51,7 @@ public final class URLQueryDecoder: Sendable { } public func decode( - _ type: T.Type, + _ type: T.Type = T.self, from query: String ) throws -> T { let options = optionsMutex.withLock { $0 } @@ -68,4 +68,25 @@ public final class URLQueryDecoder: Sendable { return try T(from: decoder) } + + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + public func decode( + _ type: T.Type = T.self, + from query: String, + configuration: T.DecodingConfiguration + ) throws -> T { + let options = optionsMutex.withLock { $0 } + + let deserializer = URLQueryDeserializer() + let value = try deserializer.deserialize(query) + + let decoder = URLQuerySingleValueDecodingContainer( + value: value, + options: options, + userInfo: userInfo, + codingPath: [] + ) + + return try T(from: decoder, configuration: configuration) + } } diff --git a/Sources/Encoder/URLQueryEncoder.swift b/Sources/Encoder/URLQueryEncoder.swift index 1e96ac6..3271a90 100644 --- a/Sources/Encoder/URLQueryEncoder.swift +++ b/Sources/Encoder/URLQueryEncoder.swift @@ -98,4 +98,36 @@ public final class URLQueryEncoder: Sendable { return serializer.serialize(urlEncodedForm) } + + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + public func encode( + _ value: T, + configuration: T.EncodingConfiguration + ) throws -> String { + let options = optionsMutex.withLock { $0 } + + let encoder = URLQuerySingleValueEncodingContainer( + options: options, + userInfo: userInfo, + codingPath: [] + ) + + try value.encode(to: encoder, configuration: configuration) + + guard case let .dictionary(urlEncodedForm) = encoder.resolveValue() else { + let errorContext = EncodingError.Context( + codingPath: [], + debugDescription: "Root component cannot be encoded in URL" + ) + + throw EncodingError.invalidValue(value, errorContext) + } + + let serializer = URLQuerySerializer( + arrayEncodingStrategy: arrayEncodingStrategy, + spaceEncodingStrategy: spaceEncodingStrategy + ) + + return serializer.serialize(urlEncodedForm) + } }