forked from MONEI/Shopify-api-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (80 loc) · 2.17 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
'use strict';
const path = require('path');
const _ = require('lodash');
const got = require('got');
const fs = require('fs');
const pkg = require('./package');
/**
* Creates a Shopify instance.
*
* @param {String} shop The name of the shop
* @param {String} key The API Key
* @param {String} password The password
* @constructor
* @public
*/
function Shopify(shop, key, password) {
if (!(this instanceof Shopify)) return new Shopify(shop, key, password);
if (!shop || !key) throw new Error('Missing required arguments');
let auth;
//
// If we have only 2 arguments, `key` is a persistent OAuth2 token.
//
if (password) {
auth = `${key}:${password}`;
} else {
this.token = key;
}
this.baseUrl = {
hostname: `${shop}.myshopify.com`,
protocol: 'https:',
auth
};
}
/**
* Sends a request to a Shopify API endpoint.
*
* @param {Object} url URL object
* @param {String} method HTTP method
* @param {String} [key] Key name to use for req/res body
* @param {Object} [params] Request body
* @return {Promise}
* @private
*/
Shopify.prototype.request = function request(url, method, key, params) {
const options = _.assign({
headers: { 'User-Agent': `${pkg.name}/${pkg.version}` },
json: true,
retries: 0,
method
}, url);
if (this.token) options.headers['X-Shopify-Access-Token'] = this.token;
if (params) {
const body = key ? { [key]: params } : params;
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(body);
}
return got(options).then(res => {
const body = res.body;
if (key) return body[key];
return body || {};
});
};
//
// Require and instantiate the resources lazily.
//
fs.readdirSync(path.join(__dirname, 'resources')).forEach(name => {
const prop = _.camelCase(name.slice(0, -3));
Object.defineProperty(Shopify.prototype, prop, {
get: function get() {
const resource = require(`./resources/${name}`);
return Object.defineProperty(this, prop, {
value: new resource(this)
})[prop];
},
set: function set(value) {
return Object.defineProperty(this, prop, { value })[prop];
}
});
});
module.exports = Shopify;