Coder Social home page Coder Social logo

Event JSON about swift-aws-lambda-runtime HOT 4 CLOSED

RyPoints avatar RyPoints commented on July 17, 2024
Event JSON

from swift-aws-lambda-runtime.

Comments (4)

sebsto avatar sebsto commented on July 17, 2024

Hello,

By default, the Lambda runtime serialize the JSON and pass it to your handler as a Request type.
The Swift AWS Lambda Event library has many Swift implementation for standard event types.

The runtime hides the raw JSON from your code, you can only access the data by using the correct Swift struct that matches the event JSON.

If you want to use different types, here are a couple of samples

HTTPAPI :

import AWSLambdaEvents
import AWSLambdaRuntime
import Foundation

@main
struct HttpApiLambda: LambdaHandler {
    init() {}
    init(context: LambdaInitializationContext) async throws {
        context.logger.info(
            "Log Level env var : \(ProcessInfo.processInfo.environment["LOG_LEVEL"] ?? "info" )")
    }

    // the return value must be either APIGatewayV2Response or any Encodable struct
    func handle(_ event: APIGatewayV2Request, context: AWSLambdaRuntimeCore.LambdaContext) async throws -> APIGatewayV2Response {

        var header = HTTPHeaders()
        do {
            context.logger.debug("HTTP API Message received")

            header["content-type"] = "application/json"

            // echo the request in the response
            let data = try JSONEncoder().encode(event)
            let response = String(data: data, encoding: .utf8)

            // if you want control on the status code and headers, return an APIGatewayV2Response
            // otherwise, just return any Encodable struct, the runtime will wrap it for you
            return APIGatewayV2Response(statusCode: .ok, headers: header, body: response)

        } catch {
            // should never happen as the decoding was made by the runtime
            // when the input event is malformed, this function is not even called
            header["content-type"] = "text/plain"
            return APIGatewayV2Response(statusCode: .badRequest, headers: header, body: "\(error.localizedDescription)")

        }
    }
}

SQS

import AWSLambdaEvents
import AWSLambdaRuntime
import Foundation

@main
struct SQSLambda: LambdaHandler {
    typealias Event = SQSEvent
    typealias Output = Void

    init() {}
    init(context: LambdaInitializationContext) async throws {
        context.logger.info(
            "Log Level env var : \(ProcessInfo.processInfo.environment["LOG_LEVEL"] ?? "info" )")
    }

    func handle(_ event: Event, context: AWSLambdaRuntimeCore.LambdaContext) async throws -> Output {

        context.logger.info("Log Level env var : \(ProcessInfo.processInfo.environment["LOG_LEVEL"] ?? "not defined" )" )
        context.logger.debug("SQS Message received, with \(event.records.count) record")

        for msg in event.records {
            context.logger.debug("Message ID   : \(msg.messageId)")
            context.logger.debug("Message body : \(msg.body)")
        }
    }
}

Lambda URL

import AWSLambdaEvents
import AWSLambdaRuntime
import Foundation

@main
struct UrlLambda: LambdaHandler {
  init() {}
  init(context: LambdaInitializationContext) async throws {
    context.logger.info(
      "Log Level env var : \(ProcessInfo.processInfo.environment["LOG_LEVEL"] ?? "info" )")
  }

  // the return value must be either APIGatewayV2Response or any Encodable struct
  func handle(_ event: FunctionURLRequest, context: AWSLambdaRuntimeCore.LambdaContext) async throws
    -> FunctionURLResponse
  {

    var header = HTTPHeaders()
    do {
      context.logger.debug("HTTP API Message received")

      header["content-type"] = "application/json"

      // echo the request in the response
      let data = try JSONEncoder().encode(event)
      let response = String(data: data, encoding: .utf8)

      // if you want control on the status code and headers, return an APIGatewayV2Response
      // otherwise, just return any Encodable struct, the runtime will wrap it for you
      return FunctionURLResponse(statusCode: .ok, headers: header, body: response)

    } catch {
      // should never happen as the decoding was made by the runtime
      // when the input event is malformed, this function is not even called
      header["content-type"] = "text/plain"
      return FunctionURLResponse(
        statusCode: .badRequest, headers: header, body: "\(error.localizedDescription)")

    }
  }
}

from swift-aws-lambda-runtime.

RyPoints avatar RyPoints commented on July 17, 2024

Will take a look at your samples when I have a moment. I'm looking at a V1 REST API and the Lambda Event JSON, so slightly different than the samples, but the answer might be in the samples if I review more. Was attempting to construct some very general function that worked for all scenarios at once for verification.

from swift-aws-lambda-runtime.

sebsto avatar sebsto commented on July 17, 2024

Hello @RyPoints
You're correct, the example I gave above is for API Gateway v2.
There is a struct definition for API Gateway v1 also. Check this file in the Lambda events project.

If you want to access the raw byte stream and be in charge of the decoding yourself, you can do that too.

Either you use the SimpleLambdaHandler with a String parameter, just like in this example
https://github.com/swift-server/swift-aws-lambda-runtime/blob/main/Examples/Echo/Lambda.swift
Or you can implement a ByteBufferLambdaHandler that gives you access to the raw byte buffer from SwiftNIO

public protocol ByteBufferLambdaHandler: LambdaRuntimeHandler {

from swift-aws-lambda-runtime.

RyPoints avatar RyPoints commented on July 17, 2024

Thanks for the additional info. I will definitely take a look at that as well. Like the dev over here. Catching up.

from swift-aws-lambda-runtime.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.