Skip to content

RestService

Norman Basham edited this page Feb 17, 2020 · 2 revisions

RestService

Source

A simple way to create a REST data service to handle failable CRUD operations (optionally in parallel).


RestService Usage

Given a model Pet:

struct Pet: Codable {
    let id: Int?
    let name: String
}

A Pet REST service that handles errors, failable model init methods, multiple calls in parallel, decoding, etc. can easily be created as shown:

class PetService: DataService<Pet> {
    init() {
        let base = "https://my-json-server.typicode.com/nbasham/pet_database"
        let path = "pets"
        super.init(base: base, path: path)
    }
}

GET one Pet

let service = PetService()
service.get(id: 0) { pet in
      print(pet)
}

GET all Pets

service.get { pets in
      print(pets)
}

GET multiple in parallel

Fetches N ids and returns when all are complete (uses DispatchGroup).

service.get(ids: [0, -1]) { pets in
      print(pets?.count) // 1 because -1 is an invalid id
}

POST

let model = Model(id: nil, name: "Bob")
service.create(model: model) { pet in
      print(pet) // Pet(id: Optional(1), name: "Bob")
}

PUT

service.update(id: id, model: updatedPet) { _ in
      print("Update complete")
}

If server returns updated object (this behavior is unspecified by REST conventions):

service.update(id: id, model: updatedPet) { pet in
      print(pet) // Updated model
}

DELETE

service.delete(id: id) {
      print("Delete complete")
}

Assumptions

  1. It is assumed routing URL's follow this pattern.
    GET     pets : Get all devices
    POST    pets : Create a new device

    GET     pets/{id} : Get the device information identified by "id"
    PUT     pets/{id} : Update the device information identified by "id"
    DELETE  pets/{id} : Delete device by "id"
  1. All errors creating models are filtered out from return values. If an app needs to bubble errors up, RestHelper.swift can be modified to recieve Result<Model, NetWorkError> instead of Model - the underlying code uses Result so it just a matter of bubbling it up.

Unit Tests

In terminal:

  1. cd $PROJECT/Tests/
  2. json-server --watch db.json
  3. Run unit tests in Xcode

JSON Server is a node pakage, info on Node installation.

Clone this wiki locally