Skip to content

Commit 2451bfa

Browse files
committed
swift format
1 parent fc1e246 commit 2451bfa

File tree

4 files changed

+217
-160
lines changed

4 files changed

+217
-160
lines changed
Lines changed: 119 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import Foundation
21
import AsyncHTTPClient
2+
import Foundation
33
import NIO
44
import NIOCore
5-
import NIOHTTP1
65
import NIOFoundationCompat
6+
import NIOHTTP1
77

88
extension HTTPClientResponse {
99
var isOk: Bool {
@@ -14,11 +14,11 @@ extension HTTPClientResponse {
1414
/// IndiePitcher SDK.
1515
/// This SDK is only intended for server-side Swift use. Do not embed the secret API key in client-side code for security reasons.
1616
public struct IndiePitcher: Sendable {
17-
private let client: HTTPClient // is sendable / thread-safe
17+
private let client: HTTPClient // is sendable / thread-safe
1818
private let apiKey: String
1919
private let requestTimeout: TimeAmount = .seconds(30)
2020
private let maxResponseSize = 1024 * 1024 * 100
21-
21+
2222
/// Creates a new instance of IndiePitcher SDK
2323
/// - Parameters:
2424
/// - client: Vapor's client instance to use to perform network requests. Uses the shared client by default.
@@ -27,196 +27,235 @@ public struct IndiePitcher: Sendable {
2727
self.client = client
2828
self.apiKey = apiKey
2929
}
30-
30+
3131
// MARK: networking
32-
32+
3333
private var commonHeaders: HTTPHeaders {
34-
get {
35-
var headers = HTTPHeaders()
36-
headers.add(name: "Authorization", value: "Bearer \(apiKey)")
37-
headers.add(name: "User-Agent", value: "IndiePitcherSwift")
38-
return headers
39-
}
34+
var headers = HTTPHeaders()
35+
headers.add(name: "Authorization", value: "Bearer \(apiKey)")
36+
headers.add(name: "User-Agent", value: "IndiePitcherSwift")
37+
return headers
4038
}
41-
39+
4240
private var jsonEncoder: JSONEncoder {
4341
let encoder = JSONEncoder()
4442
encoder.dateEncodingStrategy = .iso8601
4543
return encoder
4644
}
47-
45+
4846
private var jsonDecoder: JSONDecoder {
4947
let decoder = JSONDecoder()
5048
decoder.dateDecodingStrategy = .iso8601
5149
return decoder
5250
}
53-
51+
5452
private func buildUri(path: String) -> String {
5553
"https://api.indiepitcher.com/v1" + path
5654
}
57-
58-
private func post<T: Codable>(path: String, body: Codable) async throws -> T {
59-
55+
56+
private func post<T: Codable>(path: String, body: Codable) async throws -> T
57+
{
58+
6059
var headers = commonHeaders
6160
headers.add(name: "Content-Type", value: "application/json")
62-
61+
6362
var request = HTTPClientRequest(url: buildUri(path: path))
6463
request.method = .POST
6564
request.headers = headers
6665
request.body = .bytes(.init(data: try jsonEncoder.encode(body)))
67-
68-
let response = try await client.execute(request, timeout: requestTimeout)
69-
let responseData = try await response.body.collect(upTo: maxResponseSize)
70-
66+
67+
let response = try await client.execute(
68+
request, timeout: requestTimeout)
69+
let responseData = try await response.body.collect(
70+
upTo: maxResponseSize)
71+
7172
guard response.isOk else {
72-
let error = try? jsonDecoder.decode(ErrorResponse.self, from: responseData)
73-
throw IndiePitcherRequestError(statusCode: response.status.code, reason: error?.reason ?? "Unknown reason")
73+
let error = try? jsonDecoder.decode(
74+
ErrorResponse.self, from: responseData)
75+
throw IndiePitcherRequestError(
76+
statusCode: response.status.code,
77+
reason: error?.reason ?? "Unknown reason")
7478
}
75-
79+
7680
return try self.jsonDecoder.decode(T.self, from: responseData)
7781
}
78-
79-
private func patch<T: Codable>(path: String, body: Codable) async throws -> T {
80-
82+
83+
private func patch<T: Codable>(path: String, body: Codable) async throws
84+
-> T
85+
{
86+
8187
var headers = commonHeaders
8288
headers.add(name: "Content-Type", value: "application/json")
83-
89+
8490
var request = HTTPClientRequest(url: buildUri(path: path))
8591
request.method = .PATCH
8692
request.headers = headers
8793
request.body = .bytes(.init(data: try jsonEncoder.encode(body)))
88-
89-
let response = try await client.execute(request, timeout: requestTimeout)
90-
let responseData = try await response.body.collect(upTo: maxResponseSize)
91-
94+
95+
let response = try await client.execute(
96+
request, timeout: requestTimeout)
97+
let responseData = try await response.body.collect(
98+
upTo: maxResponseSize)
99+
92100
guard response.isOk else {
93-
let error = try? jsonDecoder.decode(ErrorResponse.self, from: responseData)
94-
throw IndiePitcherRequestError(statusCode: response.status.code, reason: error?.reason ?? "Unknown reason")
101+
let error = try? jsonDecoder.decode(
102+
ErrorResponse.self, from: responseData)
103+
throw IndiePitcherRequestError(
104+
statusCode: response.status.code,
105+
reason: error?.reason ?? "Unknown reason")
95106
}
96-
107+
97108
return try self.jsonDecoder.decode(T.self, from: responseData)
98109
}
99-
110+
100111
private func get<T: Codable>(path: String) async throws -> T {
101-
112+
102113
let headers = commonHeaders
103-
114+
104115
var request = HTTPClientRequest(url: buildUri(path: path))
105116
request.method = .GET
106117
request.headers = headers
107-
108-
let response = try await client.execute(request, timeout: requestTimeout)
109-
let responseData = try await response.body.collect(upTo: maxResponseSize)
110-
118+
119+
let response = try await client.execute(
120+
request, timeout: requestTimeout)
121+
let responseData = try await response.body.collect(
122+
upTo: maxResponseSize)
123+
111124
guard response.isOk else {
112-
let error = try? jsonDecoder.decode(ErrorResponse.self, from: responseData)
113-
throw IndiePitcherRequestError(statusCode: response.status.code, reason: error?.reason ?? "Unknown reason")
125+
let error = try? jsonDecoder.decode(
126+
ErrorResponse.self, from: responseData)
127+
throw IndiePitcherRequestError(
128+
statusCode: response.status.code,
129+
reason: error?.reason ?? "Unknown reason")
114130
}
115-
131+
116132
return try self.jsonDecoder.decode(T.self, from: responseData)
117133
}
118-
134+
119135
// MARK: API calls
120-
136+
121137
/// Add a new contact to the mailing list, or update an existing one if `updateIfExists` is set to `true`.
122138
/// - Parameter contact: Contact properties.
123139
/// - Returns: Created contact.
124-
@discardableResult public func addContact(contact: CreateContact) async throws -> DataResponse<Contact> {
140+
@discardableResult public func addContact(contact: CreateContact)
141+
async throws -> DataResponse<Contact>
142+
{
125143
try await post(path: "/contacts/create", body: contact)
126144
}
127-
145+
128146
/// Add miultiple contacts (up to 100) using a single API call to avoid being rate limited. Payloads with `updateIfExists` is set to `true` will be updated if a contact with given email already exists.
129147
/// - Parameter contacts: Contact properties
130148
/// - Returns: A generic empty response.
131-
@discardableResult public func addContacts(contacts: [CreateContact]) async throws -> EmptyResposne {
132-
149+
@discardableResult public func addContacts(contacts: [CreateContact])
150+
async throws -> EmptyResposne
151+
{
152+
133153
struct Payload: Codable {
134154
let contacts: [CreateContact]
135155
}
136-
137-
return try await post(path: "/contacts/create_many", body: Payload(contacts: contacts))
156+
157+
return try await post(
158+
path: "/contacts/create_many", body: Payload(contacts: contacts))
138159
}
139-
160+
140161
/// Updates a contact with given email address. This call will fail if a contact with provided email does not exist, use `addContact` instead in such case.
141162
/// - Parameter contact: Contact properties to update
142163
/// - Returns: Updated contact.
143-
@discardableResult public func updateContact(contact: UpdateContact) async throws -> DataResponse<Contact> {
164+
@discardableResult public func updateContact(contact: UpdateContact)
165+
async throws -> DataResponse<Contact>
166+
{
144167
try await patch(path: "/contacts/update", body: contact)
145168
}
146-
169+
147170
/// Deletes a contact with provided email from the mailing list
148171
/// - Parameter email: The email address of the contact you wish to remove from the mailing list
149172
/// - Returns: A generic empty response.
150-
@discardableResult public func deleteContact(email: String) async throws -> EmptyResposne {
151-
173+
@discardableResult public func deleteContact(email: String) async throws
174+
-> EmptyResposne
175+
{
176+
152177
struct Payload: Codable {
153178
var email: String
154179
}
155-
156-
return try await post(path: "/contacts/delete", body: Payload(email: email))
180+
181+
return try await post(
182+
path: "/contacts/delete", body: Payload(email: email))
157183
}
158-
184+
159185
/// Returns a paginated list of stored contacts in the mailing list.
160186
/// - Parameters:
161187
/// - page: Page to fetch, the first page has index 1.
162188
/// - perPage: How many contacts to return per page.
163189
/// - Returns: A paginated array of contacts
164-
public func listContacts(page: Int = 1, perPage: Int = 10) async throws -> PagedDataResponse<Contact> {
190+
public func listContacts(page: Int = 1, perPage: Int = 10) async throws
191+
-> PagedDataResponse<Contact>
192+
{
165193
try await get(path: "/contacts?page=\(page)&per=\(perPage)")
166194
}
167-
195+
168196
/// Sends an email to specified email address.
169197
/// The email is not required to belong to a contact in your contact lsit. Use this API to send emails such as that a user who is not signed up for your product was invited to a team.
170198
/// - Parameter data: Input params.
171199
/// - Returns: A genereic response with no return data.
172-
@discardableResult public func sendEmail(data: SendEmail) async throws -> EmptyResposne {
200+
@discardableResult public func sendEmail(data: SendEmail) async throws
201+
-> EmptyResposne
202+
{
173203
try await post(path: "/email/transactional", body: data)
174204
}
175-
205+
176206
/// Send a personalized email to one more (up to 100 using 1 API call) contacts subscribed to a proviced mailing list. This is the recommended way to send an email to members of a team of your product.
177207
/// All provided emails must belong to your mailing list and must be members of provided mailing list. All contacts are automatically subscribed to `important` default mailing list. You can use peronalization tags such as `Hi {{firstName}}` to peronalize individual sent emails, and scheduled it to be sent with a delay.
178208
/// - Parameter data: Input params.
179209
/// - Returns: A genereic response with no return data.
180-
@discardableResult public func sendEmailToContact(data: SendEmailToContact) async throws -> EmptyResposne {
210+
@discardableResult public func sendEmailToContact(data: SendEmailToContact)
211+
async throws -> EmptyResposne
212+
{
181213
try await post(path: "/email/contact", body: data)
182214
}
183-
215+
184216
/// Send a personalized email to all contacts subscribed to a provided mailing list. This is the recommendat way to send a newsletter, by creating a list called something like `Newsletter`.
185217
/// All contacts are automatically subscribed to `important` default mailing list. You can use peronalization tags such as `Hi {{firstName}}` to peronalize individual sent emails, and scheduled it to be sent with a delay.
186218
/// - Parameter data: Input params.
187219
/// - Returns: A genereic response with no return data.
188-
@discardableResult public func sendEmailToMailingList(data: SendEmailToMailingList) async throws -> EmptyResposne {
220+
@discardableResult public func sendEmailToMailingList(
221+
data: SendEmailToMailingList
222+
) async throws -> EmptyResposne {
189223
try await post(path: "/email/list", body: data)
190224
}
191-
225+
192226
/// Returns mailing lists contacts can subscribe to.
193227
/// - Parameters:
194228
/// - page: Page to fetch, the first page has index 1.
195229
/// - perPage: How many contacts to return per page.
196230
/// - Returns: A paginated array of mailing lists
197-
public func listMailingLists(page: Int = 1, perPage: Int = 10) async throws -> PagedDataResponse<MailingList> {
198-
231+
public func listMailingLists(page: Int = 1, perPage: Int = 10) async throws
232+
-> PagedDataResponse<MailingList>
233+
{
234+
199235
struct Payload: Codable {
200236
let page: Int
201237
let per: Int
202238
}
203-
239+
204240
return try await get(path: "/lists?page=\(page)&per=\(perPage)")
205241
}
206-
207-
242+
208243
/// Generates a new public URL for a contact with provided email to manage their mailing list subscriptions.
209244
/// - Parameters:
210245
/// - contactEmail: The email of a contact in your project's contact list, who to create the portal session for.
211246
/// - returnURL: The URL to redirect to when the user is done editing their mailing list, or when the session has expired.
212247
/// - Returns: The URL to redirect your user to, and the expiration date of the session.
213-
public func createMailingListsPortalSession(contactEmail: String, returnURL: URL) async throws -> DataResponse<MailingListPortalSession> {
214-
248+
public func createMailingListsPortalSession(
249+
contactEmail: String, returnURL: URL
250+
) async throws -> DataResponse<MailingListPortalSession> {
251+
215252
struct Payload: Codable {
216253
let contactEmail: String
217254
let returnURL: URL
218255
}
219-
220-
return try await post(path: "/lists/portal_session", body: Payload(contactEmail: contactEmail, returnURL: returnURL))
256+
257+
return try await post(
258+
path: "/lists/portal_session",
259+
body: Payload(contactEmail: contactEmail, returnURL: returnURL))
221260
}
222261
}

0 commit comments

Comments
 (0)