forked from magento/magento2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebapi.js
199 lines (175 loc) · 6.97 KB
/
webapi.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
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* jshint define: true */
(function (factory) {
if (typeof define === 'function' && define.amd) {
define([
"jquery",
"mage/mage"
], factory);
} else {
factory(jQuery);
}
}(function ($) {
"use strict";
/**
* Webapi object constructor
*
* @param {string} baseUrl Base URL
* @param {Object|undefined} ajaxArgs Arguments for AJAX API call
* @see http://api.jquery.com/jQuery.ajax/
* @returns {{method: Object, call: Function}}
*/
$.mage.Webapi = function(baseUrl, ajaxArgs) {
/**
* Resource-related parameters. Further extended by other domain objects like Product, etc.
*
* @const
* @type {{uri: {base: string}}}
*/
this.resource = {
uri: {
base: '', // Initialized below
api: '/webapi/rest'
}
};
/**
*
*
* @const
* @type {{create: string, update: string, get: string, delete: string}}
*/
this.method = {
'create': 'POST',
'update': 'PUT',
'get': 'GET',
'delete': 'DELETE'
};
var validMethods = [this.method.create, this.method.update, this.method.get, this.method['delete']];
// Check whether passed options comply with what we allow
if (ajaxArgs && typeof ajaxArgs !== 'object') {
throw 'ajaxArgs expected to be object';
}
if (!(baseUrl && typeof baseUrl === 'string')) {
throw 'String baseUrl parameter required';
}
// Ensure that baseUrl doesn't have ending forward slash
this.resource.uri.base = baseUrl[baseUrl.length - 1] === '/' ? baseUrl.substr(0, baseUrl.length - 1) : baseUrl;
/**
* Makes an API request
*
* @param {string} resourceUri Resource URI request to be sent to, e.g. '/v1/products/'
* @param {string} method Request method, e.g. GET, POST, etc.
* @param {*} data Payload to be sent to the server
* @param {string|undefined} version Optional: API version, e.g. 'v1' (if not specified
* using URI)
* @returns {jqXHR}
*/
this.call = function(resourceUri, method, data, version) {
/**
* Helper function to validate request method
*
* @param {string} method
* @returns {string}
*/
function validateMethod(method) {
if (validMethods.indexOf(method) === -1) {
throw 'Method name is not valid: ' + method;
}
return method;
}
var that = this;
/**
* Helper function to construct URIs
*
* @param {string} resourceUri Resource URI request to be sent to, e.g. '/v1/products/'
* @param {string} method Request method, e.g. GET, POST, etc.
* @param {*} data Payload to be sent to the server
* @param {string|undefined} version Optional: API version, e.g. 'v1'
*
* @returns {string}
*/
function getUrl(resourceUri, method, data, version) {
function ensureForwardSlash(str) {
return str[0] === '/' ? str : '/' + str;
}
if (version) {
resourceUri = version + ensureForwardSlash(resourceUri);
}
if (data && [that.method.get, that.method['delete']].indexOf(method) !== -1) {
// Append data for GET and DELETE request methods as it's simple ID (usually int)
resourceUri += data;
}
return that.resource.uri.base + that.resource.uri.api + ensureForwardSlash(resourceUri);
}
var ajaxOptions = {
url: getUrl(resourceUri, method, data, version),
type: validateMethod(method),
data: data,
dataType: 'text',
timeout: 5000,
processData: false, // Otherwise jQuery will try to append 'data' to query URL
cache: false, // Disable browser cache for GET requests
beforeSend: function (request) {
request.setRequestHeader('Accept', 'application/json');
}
};
$.extend(ajaxOptions, ajaxArgs);
return $.ajax(ajaxOptions);
};
return this;
};
$.mage.Webapi.prototype.constructor = $.mage.Webapi;
/**
* Syntax sugar over call(). Example usage: $.mage.webapi.Product('v1').get({...})
*
* @param {string} version API version (e.g. 'v1')
* @returns {{get: Function, create: Function}}
*/
$.mage.Webapi.prototype.Product = function(version) {
if (!(typeof version === 'string' && /v\d+/i.test(version))) {
throw 'Incorrect version format: ' + version;
}
version = version.toLowerCase();
var that = this; // Points to $.mage.webapi
that.resource.uri.products = '/products/';
return {
/**
* Retrieves information about specific product
*
* @param idObj Object which helps to identify the product, e.g. {id: 1}
* @returns {jqXHR}
*/
get: function(idObj) {
if (!idObj.hasOwnProperty('id')) {
throw '"id" property expected in the object';
}
return that.call(that.resource.uri.products, that.method.get, idObj.id, version);
},
/**
* Create a new product
*
* @param productData Example product data:
* productData = {
* "type_id": "simple",
* "attribute_set_id": 4,
* "sku": "1234567890",
* "weight": 1,
* "status": 1,
* "visibility": 4,
* "name": "Simple Product",
* "description": "Simple Description",
* "short_description": "Simple Short Description",
* "price": 99.95,
* "tax_class_id": 0
* };
* @returns {jqXHR}
*/
create: function(productData) {
return that.call(that.resource.uri.products, that.method.create, productData, version);
}
};
};
}));