AWS Lambda ローカルテスト(swift)

3 min読了の目安(約2700字TECH技術記事

Environment

2020/11/11

software version
Swift 5.3
macOS 10.15.7

Swift Package を作成

Xcode で Control + Shift + Command + N
HelloLambda という名前でパッケージを作成しました

Package.swift を編集

Package.swift
// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "HelloLambda",
    platforms: [.macOS(.v10_15)],
    products: [
        .executable(
            name: "HelloLambda",
            targets: ["HelloLambda"])
    ],
    dependencies: [
        .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
                 .upToNextMajor(from: "0.3.0"))
    ],
    targets: [
        .target(
            name: "HelloLambda",
            dependencies: [
                .product(name: "AWSLambdaRuntime",
                         package: "swift-aws-lambda-runtime"),
                .product(name: "AWSLambdaEvents",
                         package: "swift-aws-lambda-runtime")
            ])
    ]
)

処理を追加

model.swift ファイルを追加

model.swift
struct Input: Codable {
    let name: String
}

struct Output: Codable {
    let message: String
}
main.swift
import AWSLambdaRuntime

Lambda.run { (context, input: Input, callback: @escaping (Result<Output, Error>) -> Void) in
    callback(.success(Output(result: "Hello, \(input.name)!")))
}

ローカルテスト

Server

環境変数を追加
Xcodeの
Edit Scheme -> Run -> Arguments -> Environment Valiables
Name: LOCAL_LAMBDA_SERVER_ENABLED
value: true

実行するとローカルサーバーが起動します

Client

Xcode からリクエスト

Xcode で Shift + Command + N
macOS -> Command Line Tool
さっき作った model.swift を追加して main.swift を編集

main.swift
import Foundation
import Combine

let input = Input(name: "Anonymous")

let request: URLRequest = {
    let url = URL(string: "http://localhost:7000/invoke")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = try! JSONEncoder().encode(input)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    return request
}()

let semaphore = DispatchSemaphore(value: 0)
defer { semaphore.wait() }

let canceller = URLSession.shared.dataTaskPublisher(for: request)
    .map { data, response in print(response); return data }
    .decode(type: Output.self, decoder: JSONDecoder())
    .sink(receiveCompletion: { result in
        print(result); semaphore.signal()
    }, receiveValue: { response in
        print(response)
    })

Server 側が起動している状態で実行するとレスポンスが返ってきます

Terminal からリクエスト

curl --header "Content-Type: application/json" --request POST --data '{"name": "Anonymous"}' http://localhost:7000/invoke


参考