Skip to content

Commit 2067f4a

Browse files
fabianfettktoso
andauthored
JSONEncoder/JSONDecoder and String convenience methods (#144)
Co-authored-by: Konrad `ktoso` Malawski <[email protected]>
1 parent 07a11c4 commit 2067f4a

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Sources/AWSLambdaRuntime/Lambda+Codable.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
//===----------------------------------------------------------------------===//
1414

1515
@_exported import AWSLambdaRuntimeCore
16+
import struct Foundation.Data
1617
import class Foundation.JSONDecoder
1718
import class Foundation.JSONEncoder
1819
import NIO
@@ -130,3 +131,17 @@ extension JSONEncoder: LambdaCodableEncoder {
130131
return buffer
131132
}
132133
}
134+
135+
extension JSONEncoder {
136+
/// Convenience method to allow encoding json directly into a `String`. It can be used to encode a payload into an `APIGateway.V2.Response`'s body.
137+
public func encodeAsString<T: Encodable>(_ value: T) throws -> String {
138+
try String(decoding: self.encode(value), as: Unicode.UTF8.self)
139+
}
140+
}
141+
142+
extension JSONDecoder {
143+
/// Convenience method to allow decoding json directly from a `String`. It can be used to decode a payload from an `APIGateway.V2.Request`'s body.
144+
public func decode<T: Decodable>(_ type: T.Type, from string: String) throws -> T {
145+
try self.decode(type, from: Data(string.utf8))
146+
}
147+
}

0 commit comments

Comments
 (0)