webapi.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. /**
  6. * @deprecated since version 2.2.0
  7. */
  8. (function (factory) {
  9. 'use strict';
  10. if (typeof define === 'function' && define.amd) {
  11. define([
  12. 'jquery',
  13. 'mage/mage'
  14. ], factory);
  15. } else {
  16. factory(jQuery);
  17. }
  18. }(function ($) {
  19. 'use strict';
  20. /**
  21. * Webapi object constructor
  22. *
  23. * @param {String} baseUrl - Base URL
  24. * @param {Object|undefined} ajaxArgs - Arguments for AJAX API call
  25. * @see http://api.jquery.com/jQuery.ajax/
  26. * @returns {{method: Object, call: Function}}
  27. */
  28. $.mage.Webapi = function (baseUrl, ajaxArgs) {
  29. var validMethods;
  30. /**
  31. * Resource-related parameters. Further extended by other domain objects like Product, etc.
  32. *
  33. * @const
  34. * @type {Object}
  35. */
  36. this.resource = {
  37. uri: {
  38. base: '', // Initialized below
  39. api: '/webapi/rest'
  40. }
  41. };
  42. /**
  43. * @const
  44. * @type {Object}
  45. */
  46. this.method = {
  47. 'create': 'POST',
  48. 'update': 'PUT',
  49. 'get': 'GET',
  50. 'delete': 'DELETE'
  51. };
  52. validMethods = [this.method.create, this.method.update, this.method.get, this.method['delete']];
  53. // Check whether passed options comply with what we allow
  54. if (ajaxArgs && typeof ajaxArgs !== 'object') {
  55. throw 'ajaxArgs expected to be object';
  56. }
  57. if (!(baseUrl && typeof baseUrl === 'string')) {
  58. throw 'String baseUrl parameter required';
  59. }
  60. // Ensure that baseUrl doesn't have ending forward slash
  61. this.resource.uri.base = baseUrl[baseUrl.length - 1] === '/' ? baseUrl.substr(0, baseUrl.length - 1) : baseUrl;
  62. /**
  63. * Makes an API request
  64. *
  65. * @param {String} resourceUri - Resource URI request to be sent to, e.g. '/v1/products/'
  66. * @param {String} method - Request method, e.g. GET, POST, etc.
  67. * @param {*} data - Payload to be sent to the server
  68. * @param {String|undefined} version - Optional: API version, e.g. 'v1' (if not specifieds using URI)
  69. * @returns {jqXHR}
  70. */
  71. this.call = function (resourceUri, method, data, version) {
  72. var that = this,
  73. ajaxOptions;
  74. /**
  75. * Helper function to validate request method
  76. *
  77. * @param {String} methodName
  78. * @returns {String}
  79. */
  80. function validateMethod(methodName) {
  81. if (validMethods.indexOf(methodName) === -1) {
  82. throw 'Method name is not valid: ' + methodName;
  83. }
  84. return methodName;
  85. }
  86. /**
  87. * Helper function to construct URIs
  88. *
  89. * @param {String} resUri - Resource URI request to be sent to, e.g. '/v1/products/'
  90. * @param {String} m - Request method, e.g. GET, POST, etc.
  91. * @param {*} payload - Payload to be sent to the server
  92. * @param {String|undefined} v - Optional: API version, e.g. 'v1'
  93. * @returns {String}
  94. */
  95. function getUrl(resUri, m, payload, v) {
  96. /**
  97. * @param {String} str
  98. * @return {String}
  99. */
  100. function ensureForwardSlash(str) {
  101. return str[0] === '/' ? str : '/' + str;
  102. }
  103. if (v) {
  104. resUri = v + ensureForwardSlash(resUri);
  105. }
  106. if (payload && [that.method.get, that.method['delete']].indexOf(m) !== -1) {
  107. // Append data for GET and DELETE request methods as it's simple ID (usually int)
  108. resUri += payload;
  109. }
  110. return that.resource.uri.base + that.resource.uri.api + ensureForwardSlash(resUri);
  111. }
  112. ajaxOptions = {
  113. url: getUrl(resourceUri, method, data, version),
  114. type: validateMethod(method),
  115. data: data,
  116. dataType: 'text',
  117. timeout: 5000,
  118. processData: false, // Otherwise jQuery will try to append 'data' to query URL
  119. cache: false, // Disable browser cache for GET requests
  120. /**
  121. * @param {Object} request
  122. */
  123. beforeSend: function (request) {
  124. request.setRequestHeader('Accept', 'application/json');
  125. }
  126. };
  127. $.extend(ajaxOptions, ajaxArgs);
  128. return $.ajax(ajaxOptions);
  129. };
  130. return this;
  131. };
  132. $.mage.Webapi.prototype.constructor = $.mage.Webapi;
  133. /**
  134. * Syntax sugar over call(). Example usage: $.mage.webapi.Product('v1').get({...})
  135. *
  136. * @param {String} version - API version (e.g. 'v1')
  137. * @returns {{get: Function, create: Function}}
  138. */
  139. $.mage.Webapi.prototype.Product = function (version) {
  140. var that = this; // Points to $.mage.webapi
  141. if (!(typeof version === 'string' && /v\d+/i.test(version))) {
  142. throw 'Incorrect version format: ' + version;
  143. }
  144. version = version.toLowerCase();
  145. that.resource.uri.products = '/products/';
  146. return {
  147. /**
  148. * Retrieves information about specific product
  149. *
  150. * @param {Object} idObj - Object which helps to identify the product, e.g. {id: 1}
  151. * @returns {jqXHR}
  152. */
  153. get: function (idObj) {
  154. if (!idObj.hasOwnProperty('id')) {
  155. throw '"id" property expected in the object';
  156. }
  157. return that.call(that.resource.uri.products, that.method.get, idObj.id, version);
  158. },
  159. /**
  160. * Create a new product
  161. *
  162. * @param {Object} productData - Example product data:
  163. * productData = {
  164. * "type_id": "simple",
  165. * "attribute_set_id": 4,
  166. * "sku": "1234567890",
  167. * "weight": 1,
  168. * "status": 1,
  169. * "visibility": 4,
  170. * "name": "Simple Product",
  171. * "description": "Simple Description",
  172. * "short_description": "Simple Short Description",
  173. * "price": 99.95,
  174. * "tax_class_id": 0
  175. * };
  176. * @returns {jqXHR}
  177. */
  178. create: function (productData) {
  179. return that.call(that.resource.uri.products, that.method.create, productData, version);
  180. }
  181. };
  182. };
  183. }));