jeudi 10 août 2017

Loading a list of objects

As you can see, my API Client has a method that takes in an endpoint. fireRequest(endpoint:, ofType:) I check the http method of endpoint to see if I'm retrieving a single object or a list of objects. I know to download a list if the method is GETALL. How else could I reason about getting objects so that I don't need to make up my own method. I have never seen this done and wondering if its bad code.

Here is where GETALL is used.

/// Responsible for Making actual API requests & Handling response
    /// Returns an observable object that conforms to JSONable protocol.
    /// Entities that confrom to JSONable just means they can be initialized with json & transformed from swift to JSON.
    func rx_fireRequest<Entity: JSONable>(_ endpoint: FirebaseEndpoint, ofType _: Entity.Type ) -> Observable<[Entity]> {

        return Observable.create { [weak self] observer in

            self?.session.dataTask(with: endpoint.request, completionHandler: { (data, response, error) in

                /// Parse response from request.
                let parsedResponse = Parser(data: data, response: response, error: error)
                    .parse()

                switch parsedResponse {

                case .error(let error):
                    observer.onError(error)
                    return

                case .success(let data):

                    var entities = [Entity]()

                    switch endpoint.method {

                    /// - Flatten JSON strucuture to retrieve a list of entities.
                    case .GETALL:

                        /// Key (underscored) is unique identifier for each entity
                        /// value is k/v pairs of entity attributes.
                        for (_, value) in data {
                            if let value = value as? [String: AnyObject], let entity = Entity(json: value) {
                                entities.append(entity)
                            }
                        }

                        /// Force downcast for generic type inference.
                        observer.onNext(entities as! [Entity])
                        //observer.onCompleted()

                    /// All other methods return JSON that can be used to initialize JSONable entities 
                    default:
                        if let entity = Entity(json: data) {
                        observer.onNext([entity] as! [Entity])
                        //observer.onCompleted()
                    } else {
                        observer.onError(NetworkError.initializationFailure)
                        }
                    }
                }
            }).resume()
            return Disposables.create()
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire