forked from nodejs/node-core-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.js
More file actions
90 lines (81 loc) · 2.02 KB
/
Copy pathrequest.js
File metadata and controls
90 lines (81 loc) · 2.02 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
'use strict';
const rp = require('request-promise-native');
const fs = require('fs');
const path = require('path');
class Request {
constructor(credentials) {
this.credentials = credentials;
}
loadQuery(file) {
const filePath = path.resolve(__dirname, 'queries', `${file}.gql`);
return fs.readFileSync(filePath, 'utf8');
}
async promise() {
return rp(...arguments);
}
async gql(name, variables, path) {
const query = this.loadQuery(name);
if (path) {
const result = await this.requestAll(query, variables, path);
return result;
} else {
const result = await this.request(query, variables);
return result;
}
}
async request(query, variables) {
const options = {
uri: 'https://api.github.com/graphql',
method: 'POST',
headers: {
'Authorization': `Basic ${this.credentials}`,
'User-Agent': 'node-core-utils'
},
json: true,
gzip: true,
body: {
query: query,
variables: variables
}
};
// console.log(options);
const result = await rp(options);
if (result.errors) {
const err = new Error('GraphQL request Error');
err.data = {
// query: query,
variables: variables,
errors: result.errors
};
throw err;
}
return result.data;
}
async requestAll(query, variables, path) {
let after = null;
let all = [];
// first page
do {
const varWithPage = Object.assign({
after
}, variables);
const data = await this.request(query, varWithPage);
let current = data;
for (const step of path) {
current = current[step];
}
// current should have:
// totalCount
// pageInfo { hasNextPage, endCursor }
// nodes
all = all.concat(current.nodes);
if (current.pageInfo.hasNextPage) {
after = current.pageInfo.endCursor;
} else {
after = null;
}
} while (after !== null);
return all;
}
}
module.exports = Request;