/
SendGridClient.swift
45 lines (32 loc) · 1.63 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
import Vapor
public final class SendGridClient: Service {
let httpClient: Client
let apiKey: String
let apiEndpoint = "https://api.sendgrid.com/v3/mail/send"
public init(client: Client, apiKey: String) {
self.httpClient = client
self.apiKey = apiKey
}
public func send(_ emails: [SendGridEmail], on worker: Worker) throws -> Future<Void> {
return try emails.map { (email) in
var headers: HTTPHeaders = [:]
headers.add(name: .contentType, value: MediaType.json.description)
headers.add(name: .authorization, value: "Bearer \(apiKey)")
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let data = try encoder.encode(email)
let body = HTTPBody(data: data)
let request = HTTPRequest(method: .POST, url: URL(string: apiEndpoint) ?? .root, headers: headers, body: body)
return try httpClient.respond(to: Request(http: request, using: httpClient.container)).map(to: Void.self, { (response) -> (Void) in
switch response.http.status {
case .ok, .accepted: return
default:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let error = try decoder.decode(SendGridError.self, from: response.http.body.data ?? Data())
throw error
}
})
}.flatten(on: worker)
}
}