Resource
public struct Resource<Model>
Resource
describes a remote resource of generic type.
The type can be fetched via HTTP(S) and parsed into the coresponding model object.
Example:
let request: URLRequest = //
let resource: Resource<String?> = Resource(request: request, parse: { data in
String(data: data, encoding: .utf8)
})
-
The request to fetch the resource remote payload
Declaration
Swift
public let request: URLRequest
-
Parses data into given model.
Declaration
Swift
public let parse: (_ data: Data) throws -> Model
-
Creates a type safe resource, which can be used to fetch it with
NetworkService
Declaration
Swift
public init(request: URLRequest, parse: @escaping (Data) throws -> Model)
Parameters
request
The request to get the remote data payload
parse
Parses data fetched with the request into given Model
-
Creates an instace of Resource where the result type is
Decodable
and can be decoded with the given decoderDeclaration
Swift
public init(request: URLRequest, decoder: JSONDecoder)
Parameters
request
The request to get the remote data payload
decoder
a decoder which can decode the payload into the model type
-
This lets one inspect the data payload before data gets parsed.
let resource: Resource<Train> = // resource.inspectData { data in print(String(bytes: data, encoding: .utf8)) }
Declaration
Swift
public func inspectData(_ inspector: @escaping (Data) -> Void) -> Resource<Model>
Parameters
inspector
closure which gets passed the data
Return Value
a new resource which gets instepcted before parsing
-
Maps a resource result to a different resource. This is useful when you have result of R which contains T and your API request a resource of T,
Declaration
Swift
public func map<T>(transform: @escaping (Model) throws -> T) -> Resource<T>
Parameters
transform
transforms the original result of the resource
Return Value
the transformed resource