Skip to content

Commit bde3d0d

Browse files
committed
ad hellojson sample
1 parent 7eadd18 commit bde3d0d

File tree

5 files changed

+185
-0
lines changed

5 files changed

+185
-0
lines changed

Examples/HelloJSON/.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
response.json
2+
samconfig.toml
3+
template.yaml
4+
Makefile

Examples/HelloJSON/Package.swift

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// swift-tools-version:6.0
2+
3+
import PackageDescription
4+
5+
// needed for CI to test the local version of the library
6+
import struct Foundation.URL
7+
8+
#if os(macOS)
9+
let platforms: [PackageDescription.SupportedPlatform]? = [.macOS(.v15)]
10+
#else
11+
let platforms: [PackageDescription.SupportedPlatform]? = nil
12+
#endif
13+
14+
let package = Package(
15+
name: "swift-aws-lambda-runtime-example",
16+
platforms: platforms,
17+
products: [
18+
.executable(name: "HelloJSON", targets: ["HelloJSON"])
19+
],
20+
dependencies: [
21+
// during CI, the dependency on local version of swift-aws-lambda-runtime is added dynamically below
22+
.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main")
23+
],
24+
targets: [
25+
.executableTarget(
26+
name: "HelloJSON",
27+
dependencies: [
28+
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime")
29+
]
30+
)
31+
]
32+
)
33+
34+
if let localDepsPath = Context.environment["LAMBDA_USE_LOCAL_DEPS"],
35+
localDepsPath != "",
36+
let v = try? URL(fileURLWithPath: localDepsPath).resourceValues(forKeys: [.isDirectoryKey]),
37+
v.isDirectory == true
38+
{
39+
// when we use the local runtime as deps, let's remove the dependency added above
40+
let indexToRemove = package.dependencies.firstIndex { dependency in
41+
if case .sourceControl(
42+
name: _,
43+
location: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
44+
requirement: _
45+
) = dependency.kind {
46+
return true
47+
}
48+
return false
49+
}
50+
if let indexToRemove {
51+
package.dependencies.remove(at: indexToRemove)
52+
}
53+
54+
// then we add the dependency on LAMBDA_USE_LOCAL_DEPS' path (typically ../..)
55+
print("[INFO] Compiling against swift-aws-lambda-runtime located at \(localDepsPath)")
56+
package.dependencies += [
57+
.package(name: "swift-aws-lambda-runtime", path: localDepsPath)
58+
]
59+
}

Examples/HelloJSON/README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Hello JSON
2+
3+
This is a simple example of an AWS Lambda function that takes a JSON structure as input parameter and returns a JSON structure as response.
4+
5+
## Code
6+
7+
The code defines a `HelloRequest` and `HelloResponse` data structure to represent the input and outpout payload. These structures are typically shared with a client project, such as an iOS application.
8+
9+
The code creates a `LambdaRuntime` struct. In it's simplest form, the initializer takes a function as argument. The function is the handler that will be invoked when an event triggers the Lambda function.
10+
11+
The handler is `(event: HelloRequest, context: LambdaContext)`. The function takes two arguments:
12+
- the event argument is a `HelloRequest`. It is the parameter passed when invoking the function.
13+
- the context argument is a `Lambda Context`. It is a description of the runtime context.
14+
15+
The function return value will be encoded to an `HelloResponse` as your Lambda function response.
16+
17+
## Build & Package
18+
19+
To build & archive the package, type the following commands.
20+
21+
```bash
22+
swift package archive --allow-network-connections docker
23+
```
24+
25+
If there is no error, there is a ZIP file ready to deploy.
26+
The ZIP file is located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/HelloJSON/HelloJSON.zip`
27+
28+
## Deploy
29+
30+
Here is how to deploy using the `aws` command line.
31+
32+
```bash
33+
# Replace with your AWS Account ID
34+
AWS_ACCOUNT_ID=012345678901
35+
36+
aws lambda create-function \
37+
--function-name HelloJSON \
38+
--zip-file fileb://.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/HelloJSON/HelloJSON.zip \
39+
--runtime provided.al2 \
40+
--handler provided \
41+
--architectures arm64 \
42+
--role arn:aws:iam::${AWS_ACCOUNT_ID}:role/lambda_basic_execution
43+
```
44+
45+
The `--architectures` flag is only required when you build the binary on an Apple Silicon machine (Apple M1 or more recent). It defaults to `x64`.
46+
47+
Be sure to define the `AWS_ACCOUNT_ID` environment variable with your actual AWS account ID (for example: 012345678901).
48+
49+
## Invoke your Lambda function
50+
51+
To invoke the Lambda function, use this `aws` command line.
52+
53+
```bash
54+
aws lambda invoke \
55+
--function-name HelloJSON \
56+
--payload $(echo '{ "name" : "Seb", "age" : 50 }' | base64) \
57+
out.txt && cat out.txt && rm out.txt
58+
```
59+
60+
Note that the payload is expected to be a valid JSON string.
61+
62+
This should output the following result.
63+
64+
```
65+
{
66+
"StatusCode": 200,
67+
"ExecutedVersion": "$LATEST"
68+
}
69+
{"greetings":"Hello Seb. You look younger than your age."}
70+
```
71+
72+
## Undeploy
73+
74+
When done testing, you can delete the Lambda function with this command.
75+
76+
```bash
77+
aws lambda delete-function --function-name HelloJSON
78+
```

Examples/HelloJSON/Sources/main.swift

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftAWSLambdaRuntime open source project
4+
//
5+
// Copyright (c) 2024 Apple Inc. and the SwiftAWSLambdaRuntime project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
import AWSLambdaRuntime
16+
import Foundation
17+
18+
// in this example we are receiving and responding with a JSON structure
19+
20+
// the data structure to represent the input parameter
21+
struct HelloRequest: Decodable {
22+
let name: String
23+
let age: Int
24+
}
25+
26+
// the data structure to represent the output response
27+
struct HelloResponse: Encodable {
28+
let greetings: String
29+
}
30+
31+
// the JSON encoder. It is created outside of the handler.
32+
// this instance is reused at each invocation.
33+
let encoder = JSONEncoder()
34+
35+
// the Lambda runtime
36+
let runtime = LambdaRuntime {
37+
(event: HelloRequest, context: LambdaContext) in
38+
39+
return HelloResponse(greetings: "Hello \(event.name). You look \(event.age > 30 ? "younger" : "older") than your age.")
40+
}
41+
42+
// start the loop
43+
try await runtime.run()

Examples/HelloJSON/out.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"greetings":"Hello Seb. You look younger than your age."}

0 commit comments

Comments
 (0)