forked from f/graphql.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphql.js
402 lines (371 loc) · 13.3 KB
/
graphql.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
(function () {
function __extend() {
var extended = {}, deep = false, i = 0, length = arguments.length
if (Object.prototype.toString.call( arguments[0] ) == '[object Boolean]') {
deep = arguments[0]
i++
}
var merge = function (obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
if (deep && Object.prototype.toString.call(obj[prop]) == '[object Object]') {
extended[prop] = __extend(true, extended[prop], obj[prop])
} else {
extended[prop] = obj[prop]
}
}
}
}
for (; i < length; i++) {
var obj = arguments[i]
merge(obj)
}
return extended
}
function __unique(array) {
return array.filter( function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
})
}
function __request(method, url, headers, data, asJson, onRequestError, callback) {
if (!url) {
return;
}
if (asJson) {
var body = JSON.stringify({query: data.query, variables: data.variables});
} else {
var body = "query=" + encodeURIComponent(data.query) + "&variables=" + encodeURIComponent(JSON.stringify(data.variables))
}
if (typeof XMLHttpRequest != 'undefined') {
var xhr = new XMLHttpRequest
xhr.open(method, url, true)
xhr.setRequestHeader('Content-Type', (asJson ? 'application/json' : 'application/x-www-form-urlencoded'))
xhr.setRequestHeader('Accept', 'application/json')
for (var key in headers) { xhr.setRequestHeader(key, headers[key]) }
xhr.onerror = function () { callback(xhr, xhr.status) }
xhr.onload = function () {
try {
callback(JSON.parse(xhr.responseText), xhr.status)
}
catch (e) {
callback(xhr, xhr.status)
}
}
xhr.send(body)
} else if (typeof require == 'function') {
var http = require('http'), https = require('https'), URL = require('url'), uri = URL.parse(url);
var req = (uri.protocol === 'https:' ? https : http).request({
protocol: uri.protocol,
hostname: uri.hostname,
port: uri.port,
path: uri.path,
method: "POST",
headers: __extend({
'Content-type': (asJson ? 'application/json' : 'application/x-www-form-urlencoded'),
'Accept': 'application/json'
}, headers)
}, function (response) {
var str = ''
response.setEncoding('utf8')
response.on('data', function (chunk) { str += chunk })
response.on('end', function () {
callback(JSON.parse(str), response.statusCode)
})
})
if (typeof onRequestError === 'function') {
req.on('error', function (err) {
onRequestError(err);
});
}
req.write(body)
req.end()
}
}
function __isTagCall(strings) {
return Object.prototype.toString.call(strings) == '[object Array]' && strings.raw
}
function GraphQLClient(url, options) {
if (!(this instanceof GraphQLClient)) {
var client = new GraphQLClient(url, options, true)
var _lazy = client._sender
for (var m in client) {
if (typeof client[m] == 'function') {
_lazy[m] = client[m].bind(client)
if (client[m].declare) _lazy[m].declare = client[m].declare.bind(client)
if (client[m].run) _lazy[m].run = client[m].run.bind(client)
}
}
return _lazy
} else if (arguments[2] !== true) {
throw new Error("You cannot create GraphQLClient instance. Please call GraphQLClient as function.")
}
if (!options)
options = {}
if (!options.fragments)
options.fragments = {}
this.url = url
this.options = options || {}
this._fragments = this.buildFragments(options.fragments)
this._sender = this.createSenderFunction()
this.createHelpers(this._sender)
}
// "fragment auth.login" will be "fragment auth_login"
FRAGMENT_SEPERATOR = "_"
// The autodeclare keyword.
GraphQLClient.AUTODECLARE_PATTERN = /\(@autodeclare\)|\(@autotype\)/
GraphQLClient.FRAGMENT_PATTERN = /\.\.\.\s*([A-Za-z0-9\.\_]+)/g
// Flattens nested object
/*
* {a: {b: {c: 1, d: 2}}} => {"a.b.c": 1, "a.b.d": 2}
*/
GraphQLClient.prototype.flatten = function (object) {
var prefix = arguments[1] || "", out = arguments[2] || {}, name
for (name in object) {
if (object.hasOwnProperty(name)) {
typeof object[name] == "object"
? this.flatten(object[name], prefix + name + FRAGMENT_SEPERATOR, out)
: out[prefix + name] = object[name]
}
}
return out
}
GraphQLClient.prototype.setUrl = function (url) {
this.url = url
return this.url
}
GraphQLClient.prototype.getUrl = function () {
return this.url
}
// Gets path from object
/*
* {a: {b: {c: 1, d: 2}}}, "a.b.c" => 1
*/
GraphQLClient.prototype.fragmentPath = function (fragments, path) {
var getter = new Function("fragments", "return fragments." + path.replace(/\./g, FRAGMENT_SEPERATOR))
var obj = getter(fragments)
if (path != "on" && (!obj || typeof obj != "string")) {
throw new Error("Fragment " + path + " not found")
}
return obj
}
GraphQLClient.prototype.collectFragments = function (query, fragments) {
var that = this
var fragmentRegexp = GraphQLClient.FRAGMENT_PATTERN
var collectedFragments = []
;(query.match(fragmentRegexp)||[]).forEach(function (fragment) {
var path = fragment.replace(fragmentRegexp, function (_, $m) {return $m})
var fragment = that.fragmentPath(fragments, path)
if (fragment) {
var pathRegexp = new RegExp(fragmentRegexp.source.replace(/\((.*)\)/, path))
if (fragment.match(pathRegexp)) {
throw new Error("Recursive fragment usage detected on " + path + ".")
}
collectedFragments.push(fragment)
// Collect sub fragments
var alreadyCollectedFragments = collectedFragments.filter(function (alreadyCollected) {
return alreadyCollected.match(new RegExp("fragment " + path))
})
if (alreadyCollectedFragments.length > 0 && fragmentRegexp.test(fragment)) {
that.collectFragments(fragment, fragments).forEach(function (fragment) {
collectedFragments.unshift(fragment)
})
}
}
})
return __unique(collectedFragments)
}
GraphQLClient.prototype.processQuery = function (query, fragments) {
if (typeof query == 'object' && query.hasOwnProperty('kind') && query.hasOwnProperty('definitions')) {
throw new Error("Do not use graphql AST to send requests. Please generate query as string first using `graphql.print(query)`")
}
var fragmentRegexp = GraphQLClient.FRAGMENT_PATTERN
var collectedFragments = this.collectFragments(query, fragments)
query = query.replace(fragmentRegexp, function (_, $m) {
return "... " + $m.split(".").join(FRAGMENT_SEPERATOR)
})
return [query].concat(collectedFragments.filter(function (fragment) {
// Remove already used fragments
return !query.match(fragment)
})).join("\n")
}
GraphQLClient.prototype.autoDeclare = function (query, variables) {
var that = this
var typeMap = {
string: "String",
number: function (value) {
return value % 1 === 0 ? "Int" : "Float";
},
boolean: "Boolean"
}
return query.replace(GraphQLClient.AUTODECLARE_PATTERN, function () {
var types = []
for (var key in variables) {
var value = variables[key]
var keyAndType = key.split("!")
var mapping = typeMap[typeof(value)]
var mappedType = typeof(mapping) === "function" ? mapping(value) : mapping
if (!key.match("!") && keyAndType[0].match(/_?id/i)) {
mappedType = "ID"
}
var type = (keyAndType[1] || mappedType)
if (type) {
types.push("$" + keyAndType[0] + ": " + type + "!")
}
}
types = types.join(", ")
return types ? "("+ types +")" : ""
})
}
GraphQLClient.prototype.cleanAutoDeclareAnnotations = function (variables) {
if (!variables) variables = {}
var newVariables = {}
for (var key in variables) {
var value = variables[key]
var keyAndType = key.split("!")
newVariables[keyAndType[0]] = value
}
return newVariables
}
GraphQLClient.prototype.buildFragments = function (fragments) {
var that = this
fragments = this.flatten(fragments || {})
var fragmentObject = {}
for (var name in fragments) {
var fragment = fragments[name]
if (typeof fragment == "object") {
fragmentObject[name] = that.buildFragments(fragment)
} else {
fragmentObject[name] = "\nfragment " + name + " " + fragment
}
}
return fragmentObject
}
GraphQLClient.prototype.buildQuery = function (query, variables) {
return this.autoDeclare(this.processQuery(query, this._fragments), variables)
}
GraphQLClient.prototype.createSenderFunction = function () {
var that = this
return function (query) {
if (__isTagCall(query)) {
return that.run(that.ql.apply(that, arguments))
}
var caller = function (variables, requestOptions) {
if (!requestOptions) requestOptions = {}
if (!variables) variables = {}
var fragmentedQuery = that.buildQuery(query, variables)
headers = __extend((that.options.headers||{}), (requestOptions.headers||{}))
return new Promise(function (resolve, reject) {
__request(that.options.method || "post", that.getUrl(), headers, {
query: fragmentedQuery,
variables: that.cleanAutoDeclareAnnotations(variables)
}, !!that.options.asJSON, that.options.onRequestError, function (response, status) {
if (status == 200) {
if (response.errors) {
reject(response.errors)
} else if (response.data) {
resolve(response.data)
} else {
resolve(response)
}
} else {
reject(response)
}
})
})
}
if (arguments.length > 1) {
return caller.apply(null, Array.prototype.slice.call(arguments, 1))
}
return caller
}
}
GraphQLClient.prototype.createHelpers = function (sender) {
var that = this
function helper(query) {
if (__isTagCall(query)) {
that.__prefix = this.prefix
that.__suffix = this.suffix
var result = that.run(that.ql.apply(that, arguments))
that.__prefix = ""
that.__suffix = ""
return result
}
var caller = sender(this.prefix + " " + query + " " + this.suffix)
if (arguments.length > 1 && arguments[1] != null) {
return caller.apply(null, Array.prototype.slice.call(arguments, 1))
} else {
return caller
}
}
var helpers = [
{method: 'mutate', type: 'mutation'},
{method: 'query', type: 'query'},
{method: 'subscribe', type: 'subscription'}
]
helpers.forEach(function (m) {
that[m.method] = function (query, variables, options) {
if (that.options.alwaysAutodeclare === true || (options && options.declare === true)) {
return helper.call({prefix: m.type + " (@autodeclare) {", suffix: "}"}, query, variables)
} else {
return helper.call({prefix: m.type, suffix: ""}, query, variables)
}
}
that[m.method].run = function (query, options) {
return that[m.method](query, options)({})
}
})
this.run = function (query) {
return sender(query, {})
}
}
GraphQLClient.prototype.fragments = function () {
return this._fragments
}
GraphQLClient.prototype.getOptions = function () {
return this.options || {}
}
GraphQLClient.prototype.headers = function (newHeaders) {
return this.options.headers = __extend(this.options.headers, newHeaders)
}
GraphQLClient.prototype.fragment = function (fragment) {
if (typeof fragment == 'string') {
var _fragment = this._fragments[fragment.replace(/\./g, FRAGMENT_SEPERATOR)]
if (!_fragment) {
throw "Fragment " + fragment + " not found!"
}
return _fragment.trim()
} else {
this.options.fragments = __extend(true, this.options.fragments, fragment)
this._fragments = this.buildFragments(this.options.fragments)
return this._fragments
}
}
GraphQLClient.prototype.ql = function (strings) {
var that = this
fragments = Array.prototype.slice.call(arguments, 1)
fragments = fragments.map(function (fragment) {
if (typeof fragment == 'string') {
return fragment.match(/fragment\s+([^\s]*)\s/)[1]
}
})
var query = (typeof strings == 'string') ? strings : strings.reduce(function (acc, seg, i) {
return acc + fragments[i - 1] + seg
})
query = this.buildQuery(query)
query = ((this.__prefix||"") + " " + query + " " + (this.__suffix||"")).trim()
return query
}
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(function () {
return (root.graphql = factory(GraphQLClient))
});
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(root.GraphQLClient)
} else {
root.graphql = factory(root.GraphQLClient)
}
}(this, function () {
return GraphQLClient
}))
})()