Skip to content

Commit

Permalink
feat: implement startCommercial endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
LosFarmosCTL committed Jan 25, 2024
1 parent 44399b0 commit b4a0795
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
21 changes: 15 additions & 6 deletions Sources/Twitch/API/Endpoints/Ads/StartCommercial.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,26 @@ import Foundation

extension Helix {
public func startCommercial(broadcasterId: String, length: Int) async throws
-> Commercial?
-> Commercial
{
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(name: "broadcaster_id", value: broadcasterId))
queryItems.append(URLQueryItem(name: "length", value: String(length)))
return try await self.request(
.post("channels/commercial"),
jsonBody: StartCommercialRequestBody(broadcasterId: broadcasterId, length: length)
).first!
}
}

private struct StartCommercialRequestBody: Encodable {
let broadcasterId: String
let length: Int

return try await self.request(.get("channels"), with: queryItems).first
enum CodingKeys: String, CodingKey {
case broadcasterId = "broadcaster_id"
case length
}
}

public struct Commercial: Codable {
public struct Commercial: Decodable {
let length: Int
let message: String
let retryAfter: Int
Expand Down
2 changes: 1 addition & 1 deletion Sources/Twitch/API/Endpoints/HelixData.swift
Original file line number Diff line number Diff line change
@@ -1 +1 @@
internal struct HelixData<T>: Codable where T: Codable { let data: [T] }
internal struct HelixData<T>: Decodable where T: Decodable { let data: [T] }
10 changes: 8 additions & 2 deletions Sources/Twitch/API/Helix.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ public final class Helix {
self.session = urlSession ?? URLSession(configuration: .default)
}

internal func request<T: Codable>(
_ request: HelixRequest, with queryItems: [URLQueryItem]? = nil
internal func request<T: Decodable>(
_ request: HelixRequest, with queryItems: [URLQueryItem]? = nil,
jsonBody: Encodable? = nil
) async throws -> [T] {
let (method, endpoint) = request.unwrap()

Expand All @@ -36,6 +37,11 @@ public final class Helix {
urlRequest.httpMethod = method
urlRequest.allHTTPHeaderFields = try? authentication.httpHeaders()

if let jsonBody {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = try JSONEncoder().encode(jsonBody)
}

let data = try await self.send(urlRequest)

let result = try? JSONDecoder().decode(HelixData<T>.self, from: data).data
Expand Down

0 comments on commit b4a0795

Please sign in to comment.