-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerApi.js
145 lines (132 loc) · 4.13 KB
/
ServerApi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/**
* A Node-friendly way to initialise a remote API. cf: RemoteApi.js in the client
*/
var URL = require('url') ;
function getOwnPropertyDescriptions(obj) {
var d = {};
Object.keys(obj).forEach(function(k){
d[k] = Object.getOwnPropertyDescriptor(obj,k) ;
});
return d ;
} ;
function callRemoteFuncBack(that,path,args) {
return new (that.ThenableProvider)(function(callback,error) {
if (!callback) callback = that.onSuccess.bind(that) ;
if (!error) error = that.onError.bind(that) ;
var uriRequest = URL.parse(path) ;
uriRequest.method = "POST" ;
that.setHttpOptions(uriRequest) ;
var tStart = Date.now() ;
var x = require(uriRequest.protocol.match(/(http|https):/)[1]).request(uriRequest, function(res){
res.setEncoding('utf8');
var body = "" ;
res.on('data', function (chunk) { body += chunk ; });
res.once('end',function(){
var contentType = res.headers['content-type'] ;
if (contentType) contentType = contentType.split(";")[0] ;
if (res.statusCode==200) {
var data = body ;
if (contentType=="application/json")
data = !data?data:JSON.parse(data,that.reviver) ;
callback(data) ;
} else {
var exc = new Error(body);
if (contentType=="application/json") {
try {
var exception = JSON.parse(body,that.reviver) ;
exc.message = exception.message || exception.error || exception.toString();
Object.defineProperties(exc, getOwnPropertyDescriptions(exception)) ;
} catch (ex2) {
exc.cause = ex2;
}
}
if (!exc.httpStatus)
Object.assign(exc,{ httpStatus: res.statusCode });
error(exc);
}
}) ;
}).on('error', function(e) {
error(e) ;
}) ;
x.setHeader("Content-Type","application/json; charset=utf-8") ;
x.write(JSON.stringify(Array.prototype.slice.call(args),that.serializer)) ;
x.end() ;
});
}
function constructApi(serverApi,baseUrl,that,api) {
Object.keys(api).forEach(function(i){
if (api[i]._isRemoteApi) {
delete api[i]._isRemoteApi ;
that[i] = {} ;
constructApi(serverApi,baseUrl+"/"+i,that[i],api[i]) ;
} else {
that[i] = function() {
return callRemoteFuncBack(serverApi,baseUrl+"/"+i+"/"+serverApi.version,arguments) ;
};
}
}) ;
}
function ServerApi(url,onLoad, ThenableProvider) {
var that = this ;
that.ThenableProvider = ThenableProvider ;
if (!onLoad) onLoad = function(){};
var u = (typeof url==='string')?URL.parse(url):url ;
var path = u.pathname.split("/") ;
if (path[path.length-1]=="")
path.pop(); // Strip any trailing "/"
that.version = Number(path[path.length-1].match(/^[0-9.]+$/)) ;
if (that.version>0) {
path.pop() ; // Strip the version number
} else {
this.version = "" ;
}
u.pathname = path.join("/") ;
url = URL.format(u) ;
var accessURL = URL.parse(url+"/"+that.version) ;
Object.keys(u).forEach(function(k){
if (!(k in accessURL))
accessURL[k] = u[k] ;
}) ;
require(u.protocol.match(/(http|https):/)[1]).get(accessURL, function(res) {
if (res.statusCode != 200) {
var ex = new Error("HTTP response "+res.statusCode+" "+url.toString()) ;
ex.errorObject = res ;
onLoad.call(that,ex) ;
} else {
res.setEncoding('utf8');
var body = "" ;
res.on('data', function (chunk) { body += chunk ; });
res.once('end',function(){
var api = JSON.parse(body) ;
constructApi(that,url,that,api) ;
onLoad.call(that,null) ;
}) ;
}
}).on('error', function(e) {
onLoad.call(that,e) ;
});
};
ServerApi.prototype.onSuccess = function(result){};
ServerApi.prototype.onError = function(error){};
ServerApi.prototype.headers = null ;
ServerApi.prototype.serializer = null ;
ServerApi.prototype.reviver = null ;
ServerApi.prototype.setHttpOptions = function(url) {
var that = this ;
if (that.headers) {
url.headers = url.headers || {} ;
Object.keys(that.headers).forEach(function(k){
url.headers[k] = that.headers[k] ;
}) ;
}
}
ServerApi.load = function(url,ThenableProvider) {
ThenableProvider = ThenableProvider || Promise ;
return new ThenableProvider(function($return,$error) {
new ServerApi(url,function(ex){
if (ex) $error(ex) ;
else $return(this) ;
},ThenableProvider) ;
});
};
module.exports = ServerApi ;