Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mastodon client improvements #45

Merged
merged 3 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions DarrarskiApp.xcworkspace/xcshareddata/swiftpm/Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@
"version" : "1.0.0"
}
},
{
"identity" : "swift-macro-testing",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-macro-testing",
"state" : {
"revision" : "10dcef36314ddfea6f60442169b0b320204cbd35",
"version" : "0.2.2"
}
},
{
"identity" : "swift-perception",
"kind" : "remoteSourceControl",
Expand All @@ -99,6 +108,15 @@
"version" : "1.1.1"
}
},
{
"identity" : "swift-snapshot-testing",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-snapshot-testing.git",
"state" : {
"revision" : "8e68404f641300bfd0e37d478683bb275926760c",
"version" : "1.15.2"
}
},
{
"identity" : "swift-syntax",
"kind" : "remoteSourceControl",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1520"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "MastodonMacrosTests"
BuildableName = "MastodonMacrosTests"
BlueprintName = "MastodonMacrosTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
21 changes: 21 additions & 0 deletions app/Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// swift-tools-version: 5.9
import CompilerPluginSupport
import PackageDescription

let package = Package(
Expand All @@ -18,8 +19,11 @@ let package = Package(
dependencies: [
.package(url: "https://github.com/ActuallyTaylor/SwiftHTMLToMarkdown.git", from: "1.1.1"),
.package(url: "https://github.com/TelemetryDeck/SwiftClient.git", from: "1.5.0"),
.package(url: "https://github.com/apple/swift-syntax.git", from: "509.0.0"),
.package(url: "https://github.com/onevcat/Kingfisher.git", from: "7.10.1"),
.package(url: "https://github.com/pointfreeco/swift-composable-architecture.git", branch: "observation-beta"),
.package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.2.0"),
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.15.2"),
],
targets: [
.target(
Expand Down Expand Up @@ -93,6 +97,7 @@ let package = Package(
.target(
name: "Mastodon",
dependencies: [
.target(name: "MastodonMacros"),
.product(name: "ComposableArchitecture", package: "swift-composable-architecture"),
],
resources: [
Expand All @@ -103,6 +108,22 @@ let package = Package(
name: "MastodonTests",
dependencies: [
.target(name: "Mastodon"),
.product(name: "InlineSnapshotTesting", package: "swift-snapshot-testing"),
.product(name: "SnapshotTesting", package: "swift-snapshot-testing"),
]
),
.macro(
name: "MastodonMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
]
),
.testTarget(
name: "MastodonMacrosTests",
dependencies: [
.target(name: "MastodonMacros"),
.product(name: "MacroTesting", package: "swift-macro-testing"),
]
),
.target(
Expand Down
48 changes: 0 additions & 48 deletions app/Sources/Mastodon/Client+Live.swift

This file was deleted.

11 changes: 5 additions & 6 deletions app/Sources/Mastodon/Client.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Dependencies
import Foundation
import XCTestDynamicOverlay

/// Mastodon API
///
Expand All @@ -15,19 +14,19 @@ public struct Client: Sendable {
public var getAccountStatuses: GetAccountStatuses
}

extension Client: TestDependencyKey {
extension Client: DependencyKey {
public static let testValue = Client(
getAccountStatuses: GetAccountStatuses(
run: unimplemented("\(Self.self).getAccountStatuses.run")
)
getAccountStatuses: GetAccountStatuses()
)

public static let previewValue = Client(
getAccountStatuses: .init { _ in
try await Task.sleep(for: .seconds(1))
return .preview
}
)
public static let liveValue = Client(
getAccountStatuses: .live
)
}

extension DependencyValues {
Expand Down
66 changes: 39 additions & 27 deletions app/Sources/Mastodon/Endpoints/GetAccountStatuses.swift
Original file line number Diff line number Diff line change
@@ -1,34 +1,12 @@
import DependenciesMacros
import Foundation

/// Get account’s statuses
///
/// [API documentation](https://docs.joinmastodon.org/methods/accounts/#statuses)
@Endpoint
public struct GetAccountStatuses: Sendable {
public typealias Run = @Sendable (Query) async throws -> [Status]

public init(run: @escaping GetAccountStatuses.Run) {
self.run = run
}

public var run: Run

public func callAsFunction(_ query: Query) async throws -> [Status] {
try await run(query)
}

public func callAsFunction(
accountId: String,
limit: Int? = nil,
excludeReplies: Bool? = nil
) async throws -> [Status] {
try await run(Query(
accountId: accountId,
limit: limit,
excludeReplies: excludeReplies
))
}
}

extension GetAccountStatuses {
public struct Query: Equatable, Sendable {
public struct Request: Equatable, Sendable {
public init(
accountId: String,
limit: Int? = nil,
Expand All @@ -43,4 +21,38 @@ extension GetAccountStatuses {
public var limit: Int?
public var excludeReplies: Bool?
}

public typealias Response = [Status]
}

extension GetAccountStatuses: HTTPEndpoint {
static func urlRequest(for request: Request) throws -> URLRequest {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "mastodon.social"
urlComponents.path = "/api/v1/accounts/\(request.accountId)/statuses"
var queryItems: [URLQueryItem] = []
if let limit = request.limit {
queryItems.append(URLQueryItem(
name: "limit",
value: "\(limit)"
))
}
if let excludeReplies = request.excludeReplies {
queryItems.append(URLQueryItem(
name: "exclude_replies",
value: "\(excludeReplies)"
))
}
if !queryItems.isEmpty {
urlComponents.queryItems = queryItems
}
guard let url = urlComponents.url else {
throw RequestBuildingError()
}
var urlRequest = URLRequest(url: url)
urlRequest.cachePolicy = .reloadRevalidatingCacheData
urlRequest.httpMethod = "GET"
return urlRequest
}
}
6 changes: 6 additions & 0 deletions app/Sources/Mastodon/Macros.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@attached(member, names: named(send), named(callAsFunction))
@attached(extension, conformances: Endpoint)
macro Endpoint() = #externalMacro(
module: "MastodonMacros",
type: "EndpointMacro"
)
9 changes: 6 additions & 3 deletions app/Sources/Mastodon/Models/Status.swift
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,12 @@ extension Status {
extension Array<Status> {
/// Source: [@[email protected] statuses](https://mastodon.social/api/v1/accounts/108131495937150285/statuses?limit=5&exclude_replies=true)
public static let preview: [Status] = {
let url = Bundle.module.url(forResource: "statuses_preview", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder.mastodon
return try! decoder.decode([Status].self, from: data)
return try! decoder.decode([Status].self, from: [Status].previewJSON)
}()

public static let previewJSON: Data = {
let url = Bundle.module.url(forResource: "statuses_preview", withExtension: "json")!
return try! Data(contentsOf: url)
}()
}
6 changes: 6 additions & 0 deletions app/Sources/Mastodon/Utilities/Endpoint.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
protocol Endpoint {
associatedtype Request
associatedtype Response
init()
var send: @Sendable (Request) async throws -> Response { get set }
}
29 changes: 29 additions & 0 deletions app/Sources/Mastodon/Utilities/HTTPClient.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Dependencies
import DependenciesMacros
import Foundation

public struct HTTPClient: Sendable {
@DependencyEndpoint
public var dataForRequest: @Sendable (URLRequest) async throws -> (Data, URLResponse)

public func data(for urlRequest: URLRequest) async throws -> (Data, URLResponse) {
try await dataForRequest(urlRequest)
}
}

extension HTTPClient: DependencyKey {
public static let testValue = HTTPClient()
public static var liveValue = HTTPClient(
dataForRequest: { request in
@Dependency(\.urlSession) var urlSession
return try await urlSession.data(for: request)
}
)
}

extension DependencyValues {
public var httpClient: HTTPClient {
get { self[HTTPClient.self] }
set { self[HTTPClient.self] = newValue }
}
}
40 changes: 40 additions & 0 deletions app/Sources/Mastodon/Utilities/HTTPEndpoint.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Dependencies
import Foundation

protocol HTTPEndpoint: Endpoint {
static func urlRequest(for request: Request) throws -> URLRequest
static func data(for urlRequest: URLRequest) async throws -> (Data, URLResponse)
static func validate(_ data: Data, _ urlResponse: URLResponse) throws
static func decode(_ data: Data) throws -> Response
}

extension HTTPEndpoint {
static var live: Self {
var endpoint = Self.init()
endpoint.send = { request in
let urlRequest = try urlRequest(for: request)
let (data, urlResponse) = try await data(for: urlRequest)
try validate(data, urlResponse)
return try decode(data)
}
return endpoint
}
}

extension HTTPEndpoint {
static func data(for urlRequest: URLRequest) async throws -> (Data, URLResponse) {
@Dependency(\.httpClient) var httpClient
return try await httpClient.data(for: urlRequest)
}

static func validate(_ data: Data, _ urlResponse: URLResponse) throws {
let statusCode = (urlResponse as? HTTPURLResponse)?.statusCode
guard let statusCode, (200..<300).contains(statusCode) else {
throw ErrorResponse(statusCode: statusCode, data: data)
}
}

static func decode(_ data: Data) throws -> Response where Response: Decodable {
try JSONDecoder.mastodon.decode(Response.self, from: data)
}
}
Loading