-
Notifications
You must be signed in to change notification settings - Fork 0
RestService
Norman Basham edited this page Feb 17, 2020
·
2 revisions
A simple way to create a REST data service to handle failable CRUD operations (optionally in parallel).
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)
}
}
let service = PetService()
service.get(id: 0) { pet in
print(pet)
}
service.get { pets in
print(pets)
}
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
}
let model = Model(id: nil, name: "Bob")
service.create(model: model) { pet in
print(pet) // Pet(id: Optional(1), name: "Bob")
}
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
}
service.delete(id: id) {
print("Delete complete")
}
- 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"
- 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 ofModel- the underlying code usesResultso it just a matter of bubbling it up.
In terminal:
- cd $PROJECT/Tests/
- json-server --watch db.json
- Run unit tests in Xcode
JSON Server is a node pakage, info on Node installation.