Skip to content

JSONEncoder/JSONDecoder and String convenience methods #144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Sources/AWSLambdaRuntime/Lambda+Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//

@_exported import AWSLambdaRuntimeCore
import struct Foundation.Data
import class Foundation.JSONDecoder
import class Foundation.JSONEncoder
import NIO
Expand Down Expand Up @@ -130,3 +131,17 @@ extension JSONEncoder: LambdaCodableEncoder {
return buffer
}
}

extension JSONEncoder {
/// 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.
public func encodeAsString<T: Encodable>(_ value: T) throws -> String {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can be refactored as
public func encodeAsString<Element: Encodable>(_ value: Element) throws -> String

try String(decoding: self.encode(value), as: Unicode.UTF8.self)
}
}

extension JSONDecoder {
/// 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.
public func decode<T: Decodable>(_ type: T.Type, from string: String) throws -> T {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can be refactored as
public func decode<Element: Decodable>(_ type: Element.Type, from string: String) throws -> Element

try self.decode(type, from: Data(string.utf8))
}
}