Last active
August 30, 2016 08:44
-
-
Save xplorld/9e75aedda914d998d60e8e915000eb27 to your computer and use it in GitHub Desktop.
Thoughts On how a good REST API library should look like
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ThoughtsOnRESTAPI.swift | |
//Thoughts On how a good REST API library should look like | |
/* | |
object mapping : entity <-> json | |
can do it by reflection? | |
hierarchical configuration: | |
- auth header (for all requests) | |
- require status code, method verb etc (one config for each request) | |
- parameter and payload | |
- able to add/read header in all layers | |
- no strange enums! | |
observation | |
integration with UIKit | |
adapt with different network libs | |
*/ | |
import UIKit | |
class LibAPI {} | |
class TongquAPI : LibAPI { | |
} | |
var API = TongquAPI(); | |
//configure should have 2 phases: | |
//init time config: declarations in the API class impl | |
//call time config: some closure that dynamically change config | |
// should have one-time config (`with`), lasting config (`config`) and `reset` | |
API.User.list.configure { | |
URI = baseURI + "/user/list" | |
method = .POST | |
payload = { //or some default generator, or some dict? | |
(page:Int, count:Int) -> String in | |
return "page=\(page)+count=\(count)" | |
} | |
acceptType = "application/json" //should have some predefined values | |
} | |
API.User.list.register { | |
users in | |
self.users = users //or some observer? | |
} | |
API.User.list.update(page:5,length:10) //and some observers/notifications are called | |
///////// | |
//some trial | |
///////// | |
/*lib*/ | |
class LibAPI { | |
var URL = NSURL(string: "http://")! | |
var method:String = "GET"; //todo:enum | |
var accept:String = "application/json" | |
} | |
extension LibAPI { | |
var request() -> SmallPromise<Response<T>> { | |
SomeHTTPAdapter.Request(method,URL,header,payload) { | |
response, error in | |
if error != null { | |
onError(error) | |
} else { | |
var object = Deserialize(response.data) | |
onSuccess(LibAPIResponse(reponse,object)) | |
} | |
} | |
} | |
} | |
/*using*/ | |
let TongquBaseURL = NSURL(string: "http://tongqu.me/api/")! | |
class TongquAPI : LibAPI { | |
override init() { | |
super.init() | |
URL = TongquBaseURL | |
} | |
} | |
extension TongquAPI { | |
class User : TongquAPI { | |
override init() { | |
super.init() | |
URL = NSURL(string: "user/", relativeToURL: URL)! | |
} | |
} | |
} | |
extension TongquAPI.User { | |
class List : User { | |
override init() { | |
super.init() | |
URL = NSURL(string: "list/", relativeToURL: URL)! | |
} | |
} | |
} | |
//print(TongquAPI.User.List().URL.absoluteURL) | |
TongquAPI.User.List() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment