forked from vapor-community/sendgrid-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SendGridClient.swift
54 lines (42 loc) · 1.59 KB
/
SendGridClient.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import Foundation
import NIO
import AsyncHTTPClient
import NIOHTTP1
import NIOFoundationCompat
public struct SendGridClient {
let apiURL = "https://api.sendgrid.com/v3/mail/send"
let httpClient: HTTPClient
let apiKey: String
private let encoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
return encoder
}()
private let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}()
public init(httpClient: HTTPClient, apiKey: String) {
self.httpClient = httpClient
self.apiKey = apiKey
}
public func send(email: SendGridEmail) async throws {
var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "Bearer \(apiKey)")
headers.add(name: "Content-Type", value: "application/json")
let response = try await httpClient.execute(
request: .init(
url: apiURL,
method: .POST,
headers: headers,
body: .data(encoder.encode(email))
)
).get()
// If the request was accepted, simply return
guard response.status != .ok && response.status != .accepted else { return }
// JSONDecoder will handle empty body by throwing decoding error
let byteBuffer = response.body ?? ByteBuffer(.init())
throw try decoder.decode(SendGridError.self, from: byteBuffer)
}
}