swift-server / swift-aws-lambda-runtime

Swift implementation of AWS Lambda Runtime
Apache License 2.0
1.13k stars 102 forks source link

Will support customization of JSONDecoder? #204

Closed WataruSuzuki closed 3 years ago

WataruSuzuki commented 3 years ago

Hi,

I am considering this library, however I found it difficult to use because JSONDecoder cannot be customized. I would like to use like this :

Lambda.decoder.dateDecodingStrategy = .formatted(someDateFormatter)
Lambda.decoder.keyDecodingStrategy = .convertFromSnakeCase

Is there any reason why defaultJSONDecoder cannot be customized by users?

If there's no particular reason, I'm thinking of I will write a patch.

Thank you!

fabianfett commented 3 years ago

Hi @WataruSuzuki,

you can already customize your jsonDecoder. However this is not really good documented.

  1. You need to use the LambdaHandler or EventLoopLambdaHandler protocol.
  2. You need to implement the method func decode(buffer: ByteBuffer) throws -> In which has a default implementation
  3. In this method you can use your custom jsonDecoder.

Your final code will look something like this:

// important to get support for ByteBuffer in JSONDecoder
import NIOFoundationCompat

struct YourHandler: LambdaHandler {
  typealias In = YourInputType
  typealias Out = YourOutputType

  let jsonDecoder = Self.createJSONDecoder()

  func handle(context: Lambda.Context, event: In, callback: @escaping (Result<Out, Error>) -> Void) {
    // your implementation
  }

  // overwrite default implementation
  func decode(buffer: ByteBuffer) throws -> In {
    self.decoder.decode(In.self, from: buffer)
  }

  private static func createJSONDecoder() -> JSONDecoder { 
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .formatted(someDateFormatter)
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    return decoder
  }
}

Does that help you?

WataruSuzuki commented 3 years ago

Hi @fabianfett

Thank you for tips. It solves my issue!!