官方 IndiePitcher Swift 语言 SDK。
在 IndiePitcher 的公共 REST API 之上提供类型安全的层。
SDK 文档可以在这里找到。
该 SDK 旨在与任何基于 Swift Nio 构建的框架一起使用 - 支持 Vapor、Hummingbird 或 AWS Lamda。
Package.swift
文件中.package(url: "https://github.com/IndiePitcher/indiepitcher-swift.git", from: "1.0.0"),
.product(name: "IndiePitcherSwift", package: "indiepitcher-swift")
您也可以使用 CLI 代替
swift package add-dependency https://github.com/IndiePitcher/indiepitcher-swift.git --from 1.0.0
swift package add-target-dependency IndiePitcherSwift --package indiepitcher-swift MyTarget
使用 SDK
.env
文件中。以下示例将假设您已将密钥添加到 IP_SECRET_API_KEY
键下。创建一个新文件,例如 Application+IndiePitcher.swift
并粘贴以下代码
import Vapor
import IndiePitcherSwift
extension Request {
var indiePitcher: IndiePitcher {
guard let apiKey = Environment.get("IP_V2_SECRET_API_KEY") else {
fatalError("IP_V2_SECRET_API_KEY env key missing")
}
return .init(client: application.http.client.shared, apiKey: apiKey)
}
}
extension Application {
var indiePitcher: IndiePitcher {
guard let apiKey = Environment.get("IP_V2_SECRET_API_KEY") else {
fatalError("IP_V2_SECRET_API_KEY env key missing")
}
return .init(client: http.client.shared, apiKey: apiKey)
}
}
这将使您可以使用 application
和 request
轻松访问 SDK 方法。
app.get { req async in
let emailBody = """
This is a sample body that supports **markdown**. HTML is also supported.
"""
try await indiePitcher.sendEmail(
data: .init(
to: "petr@indiepitcher.com", subject: "Hello from Vapor!", body: emailBody,
bodyFormat: .markdown))
return "ok"
}
请参阅 完整的示例存储库。
public func buildApplication(_ arguments: some AppArguments) async throws
-> some ApplicationProtocol
{
let environment = try await Environment().merging(with: .dotEnv())
let logger = {
var logger = Logger(label: "HummingbirdExample")
logger.logLevel =
arguments.logLevel ?? environment.get("LOG_LEVEL").flatMap {
Logger.Level(rawValue: $0)
} ?? .info
return logger
}()
guard let apiKey = environment.get("INDIEPITCHER_SECRET_KEY") else {
preconditionFailure("Requires \"INDIEPITCHER_SECRET_KEY\" environment variable")
}
let indiePitcher = IndiePitcher(apiKey: apiKey)
let router = buildRouter(indiePitcher: indiePitcher)
let app = Application(
router: router,
configuration: .init(
address: .hostname(arguments.hostname, port: arguments.port),
serverName: "HummingbirdExample"
),
logger: logger
)
return app
}
请参阅 完整的示例存储库。
以下是如何从 AWS Lambda 函数中发送电子邮件。请参阅 完整的示例存储库。
@main
struct MyLambda: SimpleLambdaHandler {
private let indiePitcherApiKey = "sc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
func handle(_ event: String, context: LambdaContext) async throws -> String {
let indiePitcher = IndiePitcher(apiKey: indiePitcherApiKey)
let emailBody = """
This is an email sent from a **AWS Lambda function**!
"""
try await indiePitcher.sendEmail(
data: .init(
to: "petr@indiepitcher.com", subject: "Hello from AWS Lambda!", body: emailBody,
bodyFormat: .markdown))
return "Email sent!"
}
}