forked from kuja/hamster
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
367 lines (318 loc) · 9.01 KB
/
Copy pathclient.js
File metadata and controls
367 lines (318 loc) · 9.01 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
var url = require('url')
, https = require('https')
, http = require('http')
, querystring = require('querystring')
, sax = require('sax')
, MemoryCache = require('./cache/memory')
module.exports = Client
/**
* EVE API client.
*
* The following list of options are recognized:
* <ul>
* <li><strong>url</strong>: Fully qualified HTTP(s) URL to EVE API server</li>
* <li><strong>cache</strong>: Cache object that handles persisting and retrieving results from cache</li>
* </ul>
*
* @exports Client as hamster.Client
* @param {Object} options Client options
* @see hamster.cache.FileCache
* @constructor
*/
function Client(options) {
options = options || {}
this._params = {}
this.seturl(options.url || 'https://api.eveonline.com')
this.setParams(options.params || {})
this.setCache(options.cache || new MemoryCache())
}
/**
* Set server URL.
*
* @param {String|Object} strOrObj URL string
*/
Client.prototype.setUrl = function (urlStr) {
this._url = url.parse(urlStr)
}
/**
* Get server URL.
*
* @param {Boolean} returnUrlObj Pass true to return URL object instead of string
* @return {String|Object} URL string or object
*/
Client.prototype.getUrl = function (returnUrlObj) {
return returnUrlObj ? this._url : url.format(this._url)
}
/**
* Set default parameter.
*
* @param {String} param Parameter name
* @param {String} value Parameter value
*/
Client.prototype.setParam = function (param, value) {
this._params[param] = value
}
/**
* Set default parameters.
*
* @param {object} params Parameters object
*/
Client.prototype.setParams = function (params) {
for (var param in params) {
if (params.hasOwnProperty(param)) {
this.setParam(param, params[param])
}
}
}
/**
* Get default parameter.
*
* @param {String} param Parameter name
* @return {String} Parameter value
*/
Client.prototype.getParam = function (param) {
if (typeof this._params[param] !== 'undefined') {
return this._params[param]
}
}
/**
* Get default parameters.
*
* @return {Object} Parameters object
*/
Client.prototype.getParams = function () {
return this._params
}
/**
* Clear default parameters.
*/
Client.prototype.clearParams = function () {
for (var param in this._params) {
if (this._params.hasOwnProperty(param)) {
delete params[param]
}
}
}
/**
* Set the cache object for this client.
*
* The cache object is responsible for storing and retrieving cached responses.
*
* Any cache object implementing <tt>set(key, value, duration)</tt> and
* <tt>get(key)</tt> methods can be used as a cache backend.
*
* @param {Object} cache Cache object
*/
Client.prototype.setCache = function (cache) {
this._cache = cache
}
/**
* Get cache object.
*
* @return {Object} Cache object
*/
Client.prototype.getCache = function () {
return this._cache
}
/**
* Gets a path name relative to the current path set with Client#setUrl().
*
* This method also supports a short hand syntax for path names, e.g.,
* <tt>'server:ServerStatus'</tt> would translate to <tt>/server/ServerStatus.xml.aspx</tt>.
*
* @param {String} path Relative path
* @return {String} Full path name
*/
Client.prototype.getPathName = function (path) {
var basePath = this.geturl(true).pathname.replace(/^\/*|\/*$/g, '')
if (path[0] !== '/') {
path = path.replace(':', '/') + '.xml.aspx'
}
if (basePath) {
basePath = '/' + basePath
}
return basePath + '/' + path.replace(/^\/*|\/*$/g, '')
}
/**
* Get request URL with specified path and params as a URL object.
*
* @param {String} path Request path
* @param {Object} params Query string parameters
* @return {Object} URL object
*/
Client.prototype.getRequestUrl = function (path, params) {
params = params || {}
var hasParams = false
, baseUrl = this.geturl(true)
, requestUrl = {}
, defaultParams = this.getParams()
for (var param in defaultParams) {
if (typeof params[param] === 'undefined') {
params[param] = defaultParams[param]
}
}
for (var param in params) {
hasParams = true
break
}
for (var key in baseUrl) {
requestUrl[key] = baseUrl[key]
}
requestUrl.pathname = this.getPathName(path)
requestUrl.path = requestUrl.pathname
if (hasParams) {
requestUrl.search = '?' + querystring.stringify(params)
requestUrl.path += requestUrl.search
}
return requestUrl
}
/**
* Takes a URL object and returns a string that will be used as the cache key
* for the resource located at the URL.
*
* Currently this just returns a URL string with query string parameters sorted
* alphabetically.
*
* @param {Object} urlObj URL object
* @return {String} Cache key
*/
Client.prototype.getCacheKey = function (urlObj) {
var keys = []
, newUrlObj = {}
, newQuery = {}
, oldQuery
for (var key in urlObj) {
newUrlObj[key] = urlObj[key]
}
if (urlObj.search) {
oldQuery = querystring.parse(urlObj.search.substr(1))
for (var key in oldQuery) {
keys.push(key)
}
// Reconstruct query with alphabetical key ordering
keys.sort().forEach(function (key) {
newQuery[key] = oldQuery[key]
})
// Insertion order should be guaranteed.
newUrlObj.search = '?' + querystring.stringify(newQuery)
newUrlObj.path = newUrlObj.pathname + newUrlObj.search
}
return url.format(newUrlObj)
}
/**
* Parses an EVE API response from either an XML string or a readable stream.
* A callback will be invoked and passed either an error or result object.
*
* @param {String|Stream} xml API response
* @param {Function} cb Result callback
*/
Client.prototype.parse = function (xml, cb) {
var parser = sax.createStream(true, {trim: true})
, result = {}
, current = result
, parents = []
, currentTag
, keys
parser.on('error', function (err) {
cb(err)
})
parser.on('end', function () {
var err = null
, res = undefined
if (result && result.eveapi && result.eveapi.error) {
err = new Error(result.eveapi.error)
err.code = result.eveapi.errorCode
} else if (!result || !result.eveapi || !result.eveapi.result) {
err = new Error('Invalid API response structure.')
} else {
if (result.eveapi.currentTime) result.eveapi.result.currentTime = result.eveapi.currentTime
if (result.eveapi.cachedUntil) result.eveapi.result.cachedUntil = result.eveapi.cachedUntil
res = result.eveapi.result
}
cb(err, res)
})
parser.on('opentag', function (tag) {
currentTag = tag
tag.alias = tag.name
tag.result = current
parents.push(tag)
if (tag.name === 'row') {
var key = keys.map(function (key) { return tag.attributes[key] }).join(':')
current[key] = {}
current = current[key]
for (var attr in tag.attributes) {
current[attr] = tag.attributes[attr]
}
} else {
if (tag.name === 'rowset') {
keys = tag.attributes.key.split(',')
tag.alias = tag.attributes.name
} else if (tag.name === 'error') {
current.errorCode = tag.attributes.code ? tag.attributes.code : null
}
current[tag.alias] = {}
current = current[tag.alias]
}
})
parser.on('closetag', function (tagName) {
current = parents.pop().result
var parentTag = parents[parents.length - 1]
if (parentTag && parentTag.name === 'rowset') {
keys = parentTag.attributes.key.split(',')
}
})
parser.on('text', function (text) {
parents[parents.length - 1].result[currentTag.name] = text
})
if (xml.pipe) {
xml.pipe(parser)
} else {
parser.write(xml)
parser.end()
}
}
/**
* Send HTTP request to API server and parse response.
*
* @param {String} path Request path
* @param {Object} params Query string parameters
* @param {Function} cb Result callback
*/
Client.prototype.fetch = function (path, params, cb) {
if (!cb) {
cb = params
params = {}
}
var options = this.getRequesturl(path, params)
, cacheKey = this.getCacheKey(options)
, cache = this.getCache()
, self = this
cache.read(cacheKey, function (err, value) {
if (err) return cb(err)
if (typeof value === 'string') return cb(null, JSON.parse(value))
var httpObj = options.protocol === 'https:' ? https : http
, request = httpObj.get(options)
options.headers = {'User-Agent': 'hamster.js'}
request.on('error', function (err) {
cb(err)
})
request.on('response', function (response) {
if (response.statusCode !== 200) {
var err = new Error('Unsupported HTTP response: ' + response.statusCode)
err.response = response
cb(err)
} else {
self.parse(response, function (err, result) {
if (err) return cb(err)
var currentTime = Date.parse(result.currentTime)
, cachedUntil = Date.parse(result.cachedUntil)
, duration = cachedUntil - currentTime
cache.write(cacheKey, JSON.stringify(result), duration, function (err) {
if (err) return cb(err)
cb(null, result)
})
})
}
})
})
}