forked from MONEI/Shopify-api-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
298 lines (248 loc) · 7.59 KB
/
index.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
'use strict';
const transform = require('lodash/transform');
const defaults = require('lodash/defaults');
const EventEmitter = require('events');
const stopcock = require('stopcock');
const got = require('got');
const url = require('url');
const pkg = require('./package');
const resources = require('./resources');
/**
* Creates a Shopify instance.
*
* @param {Object} options Configuration options
* @param {String} options.shopName The name of the shop
* @param {String} options.apiKey The API Key
* @param {String} options.password The private app password
* @param {String} options.accessToken The persistent OAuth public app token
* @param {String} [options.apiVersion] The Shopify API version to use
* @param {Boolean} [options.presentmentPrices] Whether to include the header to
* pull presentment prices for products
* @param {Boolean|Object} [options.autoLimit] Limits the request rate
* @param {Number} [options.timeout] The request timeout
* @constructor
* @public
*/
function Shopify(options) {
if (!(this instanceof Shopify)) return new Shopify(options);
if (
!options ||
!options.shopName ||
(!options.accessToken && (!options.apiKey || !options.password)) ||
(options.accessToken && (options.apiKey || options.password))
) {
throw new Error('Missing or invalid options');
}
EventEmitter.call(this);
this.options = defaults(options, { timeout: 60000 });
//
// API call limits, updated with each request.
//
this.callLimits = {
remaining: undefined,
current: undefined,
max: undefined
};
this.callGraphqlLimits = {
remaining: undefined,
current: undefined,
max: undefined
};
this.baseUrl = {
hostname: !options.shopName.endsWith('.myshopify.com')
? `${options.shopName}.myshopify.com`
: options.shopName,
protocol: 'https:'
};
if (!options.accessToken) {
this.baseUrl.username = options.apiKey;
this.baseUrl.password = options.password;
}
if (options.autoLimit) {
const conf = transform(
options.autoLimit,
(result, value, key) => {
if (key === 'calls') key = 'limit';
result[key] = value;
},
{ bucketSize: 35 }
);
this.request = stopcock(this.request, conf);
}
}
Object.setPrototypeOf(Shopify.prototype, EventEmitter.prototype);
/**
* Updates API call limits.
*
* @param {String} header X-Shopify-Shop-Api-Call-Limit header
* @private
*/
Shopify.prototype.updateLimits = function updateLimits(header) {
if (!header) return;
const limits = header.split('/').map(Number);
const callLimits = this.callLimits;
callLimits.remaining = limits[1] - limits[0];
callLimits.current = limits[0];
callLimits.max = limits[1];
this.emit('callLimits', callLimits);
};
/**
* Sends a request to a Shopify API endpoint.
*
* @param {Object} uri URL object
* @param {String} method HTTP method
* @param {(String|undefined)} key Key name to use for req/res body
* @param {(Object|undefined)} data Request body
* @param {(Object|undefined)} headers Extra headers
* @return {Promise}
* @private
*/
Shopify.prototype.request = function request(uri, method, key, data, headers) {
const options = {
headers: { 'User-Agent': `${pkg.name}/${pkg.version}`, ...headers },
timeout: this.options.timeout,
responseType: 'json',
retry: 0,
method
};
if (this.options.accessToken) {
options.headers['X-Shopify-Access-Token'] = this.options.accessToken;
}
if (data) {
options.json = key ? { [key]: data } : data;
}
return got(uri, options).then(
(res) => {
const body = res.body;
this.updateLimits(res.headers['x-shopify-shop-api-call-limit']);
if (res.statusCode === 202) {
const retryAfter = res.headers['retry-after'] * 1000 || 0;
const { pathname, search } = url.parse(res.headers['location']);
return delay(retryAfter).then(() => {
const uri = { pathname, ...this.baseUrl };
if (search) uri.search = search;
return this.request(uri, 'GET', key);
});
}
const data = key ? body[key] : body || {};
if (res.headers.link) {
const link = parseLinkHeader(res.headers.link);
if (link.next) {
Object.defineProperties(data, {
nextPageParameters: { value: link.next.query }
});
}
if (link.previous) {
Object.defineProperties(data, {
previousPageParameters: { value: link.previous.query }
});
}
}
return data;
},
(err) => {
this.updateLimits(
err.response && err.response.headers['x-shopify-shop-api-call-limit']
);
return Promise.reject(err);
}
);
};
/**
* Updates GraphQL API call limits.
*
* @param {String} throttle The status returned in the GraphQL response
* @private
*/
Shopify.prototype.updateGraphqlLimits = function updateGraphqlLimits(throttle) {
if (!throttle) return;
const limits = this.callGraphqlLimits;
limits.remaining = throttle.currentlyAvailable;
limits.current = throttle.maximumAvailable - throttle.currentlyAvailable;
limits.max = throttle.maximumAvailable;
this.emit('callGraphqlLimits', limits);
};
/**
* Sends a request to the Shopify GraphQL API endpoint.
*
* @param {String} [data] Request body
* @return {Promise}
* @public
*/
Shopify.prototype.graphql = function graphql(data, variables) {
let pathname = '/admin/api';
if (this.options.apiVersion) {
pathname += `/${this.options.apiVersion}`;
}
pathname += '/graphql.json';
const uri = { pathname, ...this.baseUrl };
const json = variables !== undefined && variables !== null;
const options = {
headers: {
'User-Agent': `${pkg.name}/${pkg.version}`,
'Content-Type': json ? 'application/json' : 'application/graphql'
},
timeout: this.options.timeout,
responseType: 'json',
retry: 0,
method: 'POST',
body: json ? JSON.stringify({ query: data, variables }) : data
};
if (this.options.accessToken) {
options.headers['X-Shopify-Access-Token'] = this.options.accessToken;
}
return got(uri, options).then((res) => {
if (res.body.extensions && res.body.extensions.cost) {
this.updateGraphqlLimits(res.body.extensions.cost.throttleStatus);
}
if (res.body.errors) {
const first = res.body.errors[0];
const err = new Error(first.message);
err.locations = first.locations;
err.path = first.path;
err.extensions = first.extensions;
err.response = res;
throw err;
}
return res.body.data || {};
});
};
resources.registerAll(Shopify);
/**
* Returns a promise that resolves after a given amount of time.
*
* @param {Number} ms Amount of milliseconds to wait
* @return {Promise} Promise that resolves after `ms` milliseconds
* @private
*/
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Parses the `Link` header into an object.
*
* @param {String} header The field value of the header
* @return {Object} The parsed header
* @private
*/
function parseLinkHeader(header) {
return header.split(',').reduce(reducer, {});
}
/**
* The callback function for `Array.prototype.reduce()` used by
* `parseLinkHeader()`.
*
* @param {Array} acc The accumulator
* @param {Object} cur The current element being processed in the array
* @return {Object} The accumulator
* @private
*/
function reducer(acc, cur) {
const pieces = cur.trim().split(';');
const link = url.parse(pieces[0].trim().slice(1, -1), true);
const rel = pieces[1].trim().slice(4);
if (rel === '"next"') acc.next = link;
else acc.previous = link;
return acc;
}
module.exports = Shopify;