Comments (4)
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.
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.
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
from swift-aws-lambda-runtime.
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)
- Replacement for Lambda.run? HOT 5
- How to fix newline in input causing Swift AWS lambda to fail in localhost testing HOT 2
- README.MD example about SimpleLambdaHandler HOT 3
- Archive plugin execution error with AWS SDK HOT 14
- Discussions repository Feature HOT 5
- Archive plugin to generate libraries (*.so) HOT 2
- [Request] Support Serverless Framework with a plugin? HOT 6
- [Idea] Could Lambda Layers Custom Runtime improve cold start performance? HOT 3
- [Feature Request] Somehow don't touch Package.resolved during lambda package archive to work better with VSCode. HOT 1
- [BUG] Can't compile code with NSFileCoordinator (cannot find in scope) HOT 3
- CI builds fails with Swift 5.9 and Swift nightly HOT 4
- [Question] Can DocC remove license headers from source code file HOT 4
- Add support for SPM Resources HOT 1
- print statements do not work despite context.logger.info(stringLiteral:) working HOT 1
- Debugging locally on a different invocation endpoint HOT 3
- Function crash details not reported HOT 6
- Compile error on Windows HOT 1
- Doesn't compile with the Linux Static SDK (aka musl)
- [plugin] add option to compile with the Static Linux SDK instead of docker HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swift-aws-lambda-runtime.