-
Notifications
You must be signed in to change notification settings - Fork 113
Add LambdaAPI Example of a Serverless REST API #125
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Andrea-Scuderi
wants to merge
10
commits into
swift-server:master
from
Andrea-Scuderi:as-add-api-example
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4974b6c
Add LambdaAPI Example of a Serverless REST API
Andrea-Scuderi e8436ff
Rename LambdaAPI to Product API
Andrea-Scuderi 563f835
Improve formatting and remove unused import
Andrea-Scuderi 9f875dc
Improve formatting
Andrea-Scuderi 4b56aa5
Refactor Operation
Andrea-Scuderi 381aecd
Remove Logging
Andrea-Scuderi c55838a
Refactor ProductService and ProductLambdaHandler
Andrea-Scuderi 2e1f458
Refactor ProductField
Andrea-Scuderi 86a89d8
Refactor APIGateway+Extension
Andrea-Scuderi 074b7a0
Store createdAt and updatedAt as TimeIntervalSince1970 in DynamoDB
Andrea-Scuderi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
Examples/LambdaFunctions/Sources/ProductAPI/APIGateway+Extensions.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftAWSLambdaRuntime open source project | ||
// | ||
// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import AWSLambdaEvents | ||
import class Foundation.JSONEncoder | ||
import class Foundation.JSONDecoder | ||
|
||
extension APIGateway.V2.Request { | ||
|
||
static private let decoder = JSONDecoder() | ||
|
||
public func bodyObject<T: Codable>() throws -> T { | ||
guard let body = self.body, | ||
let dataBody = body.data(using: .utf8) | ||
else { | ||
throw APIError.invalidRequest | ||
} | ||
return try Self.decoder.decode(T.self, from: dataBody) | ||
} | ||
} | ||
|
||
extension APIGateway.V2.Response { | ||
|
||
private static let encoder = JSONEncoder() | ||
|
||
public static let defaultHeaders = [ | ||
"Content-Type": "application/json", | ||
//Security warning: XSS are enabled | ||
"Access-Control-Allow-Origin": "*", | ||
"Access-Control-Allow-Methods": "OPTIONS,GET,POST,PUT,DELETE", | ||
"Access-Control-Allow-Credentials": "true", | ||
] | ||
|
||
public init(with error: Error, statusCode: AWSLambdaEvents.HTTPResponseStatus) { | ||
self.init( | ||
statusCode: statusCode, | ||
headers: APIGateway.V2.Response.defaultHeaders, | ||
multiValueHeaders: nil, | ||
body: "{\"message\":\"\(String(describing: error))\"}", | ||
isBase64Encoded: false | ||
) | ||
} | ||
|
||
public init<Out: Encodable>(with object: Out, statusCode: AWSLambdaEvents.HTTPResponseStatus) { | ||
var body: String = "{}" | ||
if let data = try? Self.encoder.encode(object) { | ||
body = String(data: data, encoding: .utf8) ?? body | ||
} | ||
self.init( | ||
statusCode: statusCode, | ||
headers: APIGateway.V2.Response.defaultHeaders, | ||
multiValueHeaders: nil, | ||
body: body, | ||
isBase64Encoded: false | ||
) | ||
} | ||
} |
57 changes: 57 additions & 0 deletions
57
Examples/LambdaFunctions/Sources/ProductAPI/Product+DynamoDB.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftAWSLambdaRuntime open source project | ||
// | ||
// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import AWSDynamoDB | ||
import Foundation | ||
|
||
extension Product { | ||
|
||
public var dynamoDictionary: [String: DynamoDB.AttributeValue] { | ||
var dictionary = [ | ||
Field.sku: DynamoDB.AttributeValue(s: sku), | ||
Field.name: DynamoDB.AttributeValue(s: name), | ||
Field.description: DynamoDB.AttributeValue(s: description), | ||
] | ||
if let createdAt = createdAt?.timeIntervalSince1970String { | ||
dictionary[Field.createdAt] = DynamoDB.AttributeValue(n: createdAt) | ||
} | ||
|
||
if let updatedAt = updatedAt?.timeIntervalSince1970String { | ||
dictionary[Field.updatedAt] = DynamoDB.AttributeValue(n: updatedAt) | ||
} | ||
return dictionary | ||
} | ||
|
||
public init(dictionary: [String: DynamoDB.AttributeValue]) throws { | ||
guard let name = dictionary[Field.name]?.s, | ||
let sku = dictionary[Field.sku]?.s, | ||
let description = dictionary[Field.description]?.s | ||
else { | ||
throw APIError.invalidItem | ||
} | ||
self.name = name | ||
self.sku = sku | ||
self.description = description | ||
if let value = dictionary[Field.createdAt]?.n, | ||
let timeInterval = TimeInterval(value) { | ||
let date = Date(timeIntervalSince1970: timeInterval) | ||
self.createdAt = date.iso8601 | ||
} | ||
if let value = dictionary[Field.updatedAt]?.n, | ||
let timeInterval = TimeInterval(value) { | ||
let date = Date(timeIntervalSince1970: timeInterval) | ||
self.updatedAt = date.iso8601 | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftAWSLambdaRuntime open source project | ||
// | ||
// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import Foundation | ||
|
||
public struct Product: Codable { | ||
public let sku: String | ||
public let name: String | ||
public let description: String | ||
public var createdAt: String? | ||
public var updatedAt: String? | ||
|
||
public struct Field { | ||
static let sku = "sku" | ||
static let name = "name" | ||
static let description = "description" | ||
static let createdAt = "createdAt" | ||
static let updatedAt = "updatedAt" | ||
} | ||
} |
101 changes: 101 additions & 0 deletions
101
Examples/LambdaFunctions/Sources/ProductAPI/ProductLambda.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftAWSLambdaRuntime open source project | ||
// | ||
// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import AWSDynamoDB | ||
import AWSLambdaEvents | ||
import AWSLambdaRuntime | ||
import AsyncHTTPClient | ||
import Logging | ||
import NIO | ||
|
||
enum Operation: String { | ||
case create | ||
case read | ||
case update | ||
case delete | ||
case list | ||
} | ||
|
||
struct EmptyResponse: Codable {} | ||
|
||
struct ProductLambda: LambdaHandler { | ||
|
||
typealias In = APIGateway.V2.Request | ||
typealias Out = APIGateway.V2.Response | ||
|
||
let dbTimeout: Int64 = 30 | ||
let region: Region | ||
let db: AWSDynamoDB.DynamoDB | ||
let service: ProductService | ||
let tableName: String | ||
let operation: Operation | ||
var httpClient: HTTPClient | ||
|
||
static func currentRegion() -> Region { | ||
if let awsRegion = Lambda.env("AWS_REGION") { | ||
let value = Region(rawValue: awsRegion) | ||
return value | ||
} else { | ||
return .useast1 | ||
} | ||
} | ||
|
||
static func tableName() throws -> String { | ||
guard let tableName = Lambda.env("PRODUCTS_TABLE_NAME") else { | ||
throw APIError.tableNameNotFound | ||
} | ||
return tableName | ||
} | ||
|
||
init(context: Lambda.InitializationContext) throws { | ||
|
||
guard let handler = Lambda.env("_HANDLER"), | ||
let operation = Operation(rawValue: handler) else { | ||
throw APIError.invalidHandler | ||
} | ||
self.operation = operation | ||
self.region = Self.currentRegion() | ||
|
||
let lambdaRuntimeTimeout: TimeAmount = .seconds(dbTimeout) | ||
let timeout = HTTPClient.Configuration.Timeout( | ||
connect: lambdaRuntimeTimeout, | ||
read: lambdaRuntimeTimeout | ||
) | ||
|
||
let configuration = HTTPClient.Configuration(timeout: timeout) | ||
self.httpClient = HTTPClient( | ||
eventLoopGroupProvider: .shared(context.eventLoop), | ||
configuration: configuration | ||
) | ||
|
||
self.db = AWSDynamoDB.DynamoDB(region: region, httpClientProvider: .shared(self.httpClient)) | ||
self.tableName = try Self.tableName() | ||
|
||
self.service = ProductService( | ||
db: db, | ||
tableName: tableName | ||
) | ||
} | ||
|
||
func handle( | ||
context: Lambda.Context, event: APIGateway.V2.Request, | ||
callback: @escaping (Result<APIGateway.V2.Response, Error>) -> Void | ||
) { | ||
let _ = ProductLambdaHandler(service: service, operation: operation) | ||
.handle(context: context, event: event) | ||
.always { (result) in | ||
callback(result) | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@tomerd / @fabianfett we need to remove all executables from the
products
. If you export it as aproduct
, then other libraries can depend on them.swift run
works on alltargets
, so just leave out everything that's not meant for other packages to depend on.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @fabianfett for pointing out to me that this isn't the main Package.swift. So we don't need to remove those here. They still aren't necessary but not an issue to have them.