Skip to content

Commit be95b65

Browse files
committed
add new example that uses an async lambda handler
1 parent 1b19191 commit be95b65

File tree

5 files changed

+75
-0
lines changed

5 files changed

+75
-0
lines changed

Examples/RESTCountries/.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
.DS_Store
2+
/.build
3+
/Packages
4+
/*.xcodeproj
+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"object": {
3+
"pins": [
4+
5+
]
6+
},
7+
"version": 1
8+
}

Examples/RESTCountries/Package.swift

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// swift-tools-version:4.2
2+
3+
import PackageDescription
4+
5+
let package = Package(
6+
name: "RESTCountries",
7+
dependencies: [
8+
.package(path: "../../"),
9+
],
10+
targets: [
11+
.target(
12+
name: "RESTCountries",
13+
dependencies: ["AWSLambdaSwift"]
14+
),
15+
]
16+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import AWSLambdaSwift
2+
import Foundation
3+
4+
struct Input: Codable {
5+
let countryCode: String
6+
}
7+
8+
struct Country: Codable {
9+
let name: String
10+
let capital: String
11+
let population: Int
12+
}
13+
14+
struct Output: Codable {
15+
let country: Country?
16+
}
17+
18+
func fetchCountry(input: Input, context: Context, completionHandler: @escaping (Output) -> Void) {
19+
guard let url = URL(string: "http://restcountries.eu/rest/v2/alpha/\(input.countryCode)") else {
20+
completionHandler(Output(country: nil))
21+
return
22+
}
23+
24+
let session = URLSession(configuration: .default)
25+
let dataTask = session.dataTask(with: url) { data, _, error in
26+
guard error == nil, let data = data else {
27+
completionHandler(Output(country: nil))
28+
return
29+
}
30+
31+
let jsonDecoder = JSONDecoder()
32+
guard let country = try? jsonDecoder.decode(Country.self, from: data) else {
33+
completionHandler(Output(country: nil))
34+
return
35+
}
36+
37+
completionHandler(Output(country: country))
38+
}
39+
dataTask.resume()
40+
}
41+
42+
let runtime = try Runtime()
43+
runtime.registerLambda("fetchCountry", handlerFunction: fetchCountry)
44+
try runtime.start()

Makefile

+3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ EXAMPLE_PROJECT_PATH=Examples/SquareNumber
44
# EXAMPLE_LAMBDA=SyntaxHighlighter
55
# EXAMPLE_EXECUTABLE=SyntaxHighlighter
66
# EXAMPLE_PROJECT_PATH=Examples/SyntaxHighlighter
7+
# EXAMPLE_LAMBDA=RESTCountries
8+
# EXAMPLE_EXECUTABLE=RESTCountries
9+
# EXAMPLE_PROJECT_PATH=Examples/RESTCountries
710
LAMBDA_ZIP=lambda.zip
811
SHARED_LIBS_FOLDER=swift-shared-libs
912
LAYER_ZIP=swift-lambda-runtime.zip

0 commit comments

Comments
 (0)