api-request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Thin jQuery.ajax wrapper for WP REST API requests.
  3. *
  4. * Currently only applies to requests that do not use the `wp-api.js` Backbone
  5. * client library, though this may change. Serves several purposes:
  6. *
  7. * - Allows overriding these requests as needed by customized WP installations.
  8. * - Sends the REST API nonce as a request header.
  9. * - Allows specifying only an endpoint namespace/path instead of a full URL.
  10. *
  11. * @since 4.9.0
  12. */
  13. ( function( $ ) {
  14. var wpApiSettings = window.wpApiSettings;
  15. function apiRequest( options ) {
  16. options = apiRequest.buildAjaxOptions( options );
  17. return apiRequest.transport( options );
  18. }
  19. apiRequest.buildAjaxOptions = function( options ) {
  20. var url = options.url;
  21. var path = options.path;
  22. var namespaceTrimmed, endpointTrimmed;
  23. var headers, addNonceHeader, headerName;
  24. if (
  25. typeof options.namespace === 'string' &&
  26. typeof options.endpoint === 'string'
  27. ) {
  28. namespaceTrimmed = options.namespace.replace( /^\/|\/$/g, '' );
  29. endpointTrimmed = options.endpoint.replace( /^\//, '' );
  30. if ( endpointTrimmed ) {
  31. path = namespaceTrimmed + '/' + endpointTrimmed;
  32. } else {
  33. path = namespaceTrimmed;
  34. }
  35. }
  36. if ( typeof path === 'string' ) {
  37. url = wpApiSettings.root + path.replace( /^\//, '' );
  38. }
  39. // If ?_wpnonce=... is present, no need to add a nonce header.
  40. addNonceHeader = ! ( options.data && options.data._wpnonce );
  41. headers = options.headers || {};
  42. // If an 'X-WP-Nonce' header (or any case-insensitive variation
  43. // thereof) was specified, no need to add a nonce header.
  44. if ( addNonceHeader ) {
  45. for ( headerName in headers ) {
  46. if ( headers.hasOwnProperty( headerName ) ) {
  47. if ( headerName.toLowerCase() === 'x-wp-nonce' ) {
  48. addNonceHeader = false;
  49. break;
  50. }
  51. }
  52. }
  53. }
  54. if ( addNonceHeader ) {
  55. // Do not mutate the original headers object, if any.
  56. headers = $.extend( {
  57. 'X-WP-Nonce': wpApiSettings.nonce
  58. }, headers );
  59. }
  60. // Do not mutate the original options object.
  61. options = $.extend( {}, options, {
  62. headers: headers,
  63. url: url
  64. } );
  65. delete options.path;
  66. delete options.namespace;
  67. delete options.endpoint;
  68. return options;
  69. };
  70. apiRequest.transport = $.ajax;
  71. /** @namespace wp */
  72. window.wp = window.wp || {};
  73. window.wp.apiRequest = apiRequest;
  74. } )( jQuery );