PageRenderTime 27ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/js/wp-api.js

http://github.com/wordpress/wordpress
JavaScript | 1547 lines | 810 code | 273 blank | 464 comment | 174 complexity | 66cd16f6c18c7dd52b5b7d2f38afef6e MD5 | raw file
Possible License(s): 0BSD
  1. /**
  2. * @output wp-includes/js/wp-api.js
  3. */
  4. (function( window, undefined ) {
  5. 'use strict';
  6. /**
  7. * Initialise the WP_API.
  8. */
  9. function WP_API() {
  10. /** @namespace wp.api.models */
  11. this.models = {};
  12. /** @namespace wp.api.collections */
  13. this.collections = {};
  14. /** @namespace wp.api.views */
  15. this.views = {};
  16. }
  17. /** @namespace wp */
  18. window.wp = window.wp || {};
  19. /** @namespace wp.api */
  20. wp.api = wp.api || new WP_API();
  21. wp.api.versionString = wp.api.versionString || 'wp/v2/';
  22. // Alias _includes to _.contains, ensuring it is available if lodash is used.
  23. if ( ! _.isFunction( _.includes ) && _.isFunction( _.contains ) ) {
  24. _.includes = _.contains;
  25. }
  26. })( window );
  27. (function( window, undefined ) {
  28. 'use strict';
  29. var pad, r;
  30. /** @namespace wp */
  31. window.wp = window.wp || {};
  32. /** @namespace wp.api */
  33. wp.api = wp.api || {};
  34. /** @namespace wp.api.utils */
  35. wp.api.utils = wp.api.utils || {};
  36. /**
  37. * Determine model based on API route.
  38. *
  39. * @param {string} route The API route.
  40. *
  41. * @return {Backbone Model} The model found at given route. Undefined if not found.
  42. */
  43. wp.api.getModelByRoute = function( route ) {
  44. return _.find( wp.api.models, function( model ) {
  45. return model.prototype.route && route === model.prototype.route.index;
  46. } );
  47. };
  48. /**
  49. * Determine collection based on API route.
  50. *
  51. * @param {string} route The API route.
  52. *
  53. * @return {Backbone Model} The collection found at given route. Undefined if not found.
  54. */
  55. wp.api.getCollectionByRoute = function( route ) {
  56. return _.find( wp.api.collections, function( collection ) {
  57. return collection.prototype.route && route === collection.prototype.route.index;
  58. } );
  59. };
  60. /**
  61. * ECMAScript 5 shim, adapted from MDN.
  62. * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
  63. */
  64. if ( ! Date.prototype.toISOString ) {
  65. pad = function( number ) {
  66. r = String( number );
  67. if ( 1 === r.length ) {
  68. r = '0' + r;
  69. }
  70. return r;
  71. };
  72. Date.prototype.toISOString = function() {
  73. return this.getUTCFullYear() +
  74. '-' + pad( this.getUTCMonth() + 1 ) +
  75. '-' + pad( this.getUTCDate() ) +
  76. 'T' + pad( this.getUTCHours() ) +
  77. ':' + pad( this.getUTCMinutes() ) +
  78. ':' + pad( this.getUTCSeconds() ) +
  79. '.' + String( ( this.getUTCMilliseconds() / 1000 ).toFixed( 3 ) ).slice( 2, 5 ) +
  80. 'Z';
  81. };
  82. }
  83. /**
  84. * Parse date into ISO8601 format.
  85. *
  86. * @param {Date} date.
  87. */
  88. wp.api.utils.parseISO8601 = function( date ) {
  89. var timestamp, struct, i, k,
  90. minutesOffset = 0,
  91. numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
  92. /*
  93. * ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
  94. * before falling back to any implementation-specific date parsing, so that’s what we do, even if native
  95. * implementations could be faster.
  96. */
  97. // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
  98. if ( ( struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec( date ) ) ) {
  99. // Avoid NaN timestamps caused by “undefined” values being passed to Date.UTC.
  100. for ( i = 0; ( k = numericKeys[i] ); ++i ) {
  101. struct[k] = +struct[k] || 0;
  102. }
  103. // Allow undefined days and months.
  104. struct[2] = ( +struct[2] || 1 ) - 1;
  105. struct[3] = +struct[3] || 1;
  106. if ( 'Z' !== struct[8] && undefined !== struct[9] ) {
  107. minutesOffset = struct[10] * 60 + struct[11];
  108. if ( '+' === struct[9] ) {
  109. minutesOffset = 0 - minutesOffset;
  110. }
  111. }
  112. timestamp = Date.UTC( struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7] );
  113. } else {
  114. timestamp = Date.parse ? Date.parse( date ) : NaN;
  115. }
  116. return timestamp;
  117. };
  118. /**
  119. * Helper function for getting the root URL.
  120. * @return {[type]} [description]
  121. */
  122. wp.api.utils.getRootUrl = function() {
  123. return window.location.origin ?
  124. window.location.origin + '/' :
  125. window.location.protocol + '//' + window.location.host + '/';
  126. };
  127. /**
  128. * Helper for capitalizing strings.
  129. */
  130. wp.api.utils.capitalize = function( str ) {
  131. if ( _.isUndefined( str ) ) {
  132. return str;
  133. }
  134. return str.charAt( 0 ).toUpperCase() + str.slice( 1 );
  135. };
  136. /**
  137. * Helper function that capitalizes the first word and camel cases any words starting
  138. * after dashes, removing the dashes.
  139. */
  140. wp.api.utils.capitalizeAndCamelCaseDashes = function( str ) {
  141. if ( _.isUndefined( str ) ) {
  142. return str;
  143. }
  144. str = wp.api.utils.capitalize( str );
  145. return wp.api.utils.camelCaseDashes( str );
  146. };
  147. /**
  148. * Helper function to camel case the letter after dashes, removing the dashes.
  149. */
  150. wp.api.utils.camelCaseDashes = function( str ) {
  151. return str.replace( /-([a-z])/g, function( g ) {
  152. return g[ 1 ].toUpperCase();
  153. } );
  154. };
  155. /**
  156. * Extract a route part based on negative index.
  157. *
  158. * @param {string} route The endpoint route.
  159. * @param {int} part The number of parts from the end of the route to retrieve. Default 1.
  160. * Example route `/a/b/c`: part 1 is `c`, part 2 is `b`, part 3 is `a`.
  161. * @param {string} [versionString] Version string, defaults to `wp.api.versionString`.
  162. * @param {boolean} [reverse] Whether to reverse the order when extracting the route part. Optional, default false.
  163. */
  164. wp.api.utils.extractRoutePart = function( route, part, versionString, reverse ) {
  165. var routeParts;
  166. part = part || 1;
  167. versionString = versionString || wp.api.versionString;
  168. // Remove versions string from route to avoid returning it.
  169. if ( 0 === route.indexOf( '/' + versionString ) ) {
  170. route = route.substr( versionString.length + 1 );
  171. }
  172. routeParts = route.split( '/' );
  173. if ( reverse ) {
  174. routeParts = routeParts.reverse();
  175. }
  176. if ( _.isUndefined( routeParts[ --part ] ) ) {
  177. return '';
  178. }
  179. return routeParts[ part ];
  180. };
  181. /**
  182. * Extract a parent name from a passed route.
  183. *
  184. * @param {string} route The route to extract a name from.
  185. */
  186. wp.api.utils.extractParentName = function( route ) {
  187. var name,
  188. lastSlash = route.lastIndexOf( '_id>[\\d]+)/' );
  189. if ( lastSlash < 0 ) {
  190. return '';
  191. }
  192. name = route.substr( 0, lastSlash - 1 );
  193. name = name.split( '/' );
  194. name.pop();
  195. name = name.pop();
  196. return name;
  197. };
  198. /**
  199. * Add args and options to a model prototype from a route's endpoints.
  200. *
  201. * @param {array} routeEndpoints Array of route endpoints.
  202. * @param {Object} modelInstance An instance of the model (or collection)
  203. * to add the args to.
  204. */
  205. wp.api.utils.decorateFromRoute = function( routeEndpoints, modelInstance ) {
  206. /**
  207. * Build the args based on route endpoint data.
  208. */
  209. _.each( routeEndpoints, function( routeEndpoint ) {
  210. // Add post and edit endpoints as model args.
  211. if ( _.includes( routeEndpoint.methods, 'POST' ) || _.includes( routeEndpoint.methods, 'PUT' ) ) {
  212. // Add any non empty args, merging them into the args object.
  213. if ( ! _.isEmpty( routeEndpoint.args ) ) {
  214. // Set as default if no args yet.
  215. if ( _.isEmpty( modelInstance.prototype.args ) ) {
  216. modelInstance.prototype.args = routeEndpoint.args;
  217. } else {
  218. // We already have args, merge these new args in.
  219. modelInstance.prototype.args = _.extend( modelInstance.prototype.args, routeEndpoint.args );
  220. }
  221. }
  222. } else {
  223. // Add GET method as model options.
  224. if ( _.includes( routeEndpoint.methods, 'GET' ) ) {
  225. // Add any non empty args, merging them into the defaults object.
  226. if ( ! _.isEmpty( routeEndpoint.args ) ) {
  227. // Set as default if no defaults yet.
  228. if ( _.isEmpty( modelInstance.prototype.options ) ) {
  229. modelInstance.prototype.options = routeEndpoint.args;
  230. } else {
  231. // We already have options, merge these new args in.
  232. modelInstance.prototype.options = _.extend( modelInstance.prototype.options, routeEndpoint.args );
  233. }
  234. }
  235. }
  236. }
  237. } );
  238. };
  239. /**
  240. * Add mixins and helpers to models depending on their defaults.
  241. *
  242. * @param {Backbone Model} model The model to attach helpers and mixins to.
  243. * @param {string} modelClassName The classname of the constructed model.
  244. * @param {Object} loadingObjects An object containing the models and collections we are building.
  245. */
  246. wp.api.utils.addMixinsAndHelpers = function( model, modelClassName, loadingObjects ) {
  247. var hasDate = false,
  248. /**
  249. * Array of parseable dates.
  250. *
  251. * @type {string[]}.
  252. */
  253. parseableDates = [ 'date', 'modified', 'date_gmt', 'modified_gmt' ],
  254. /**
  255. * Mixin for all content that is time stamped.
  256. *
  257. * This mixin converts between mysql timestamps and JavaScript Dates when syncing a model
  258. * to or from the server. For example, a date stored as `2015-12-27T21:22:24` on the server
  259. * gets expanded to `Sun Dec 27 2015 14:22:24 GMT-0700 (MST)` when the model is fetched.
  260. *
  261. * @type {{toJSON: toJSON, parse: parse}}.
  262. */
  263. TimeStampedMixin = {
  264. /**
  265. * Prepare a JavaScript Date for transmitting to the server.
  266. *
  267. * This helper function accepts a field and Date object. It converts the passed Date
  268. * to an ISO string and sets that on the model field.
  269. *
  270. * @param {Date} date A JavaScript date object. WordPress expects dates in UTC.
  271. * @param {string} field The date field to set. One of 'date', 'date_gmt', 'date_modified'
  272. * or 'date_modified_gmt'. Optional, defaults to 'date'.
  273. */
  274. setDate: function( date, field ) {
  275. var theField = field || 'date';
  276. // Don't alter non parsable date fields.
  277. if ( _.indexOf( parseableDates, theField ) < 0 ) {
  278. return false;
  279. }
  280. this.set( theField, date.toISOString() );
  281. },
  282. /**
  283. * Get a JavaScript Date from the passed field.
  284. *
  285. * WordPress returns 'date' and 'date_modified' in the timezone of the server as well as
  286. * UTC dates as 'date_gmt' and 'date_modified_gmt'. Draft posts do not include UTC dates.
  287. *
  288. * @param {string} field The date field to set. One of 'date', 'date_gmt', 'date_modified'
  289. * or 'date_modified_gmt'. Optional, defaults to 'date'.
  290. */
  291. getDate: function( field ) {
  292. var theField = field || 'date',
  293. theISODate = this.get( theField );
  294. // Only get date fields and non null values.
  295. if ( _.indexOf( parseableDates, theField ) < 0 || _.isNull( theISODate ) ) {
  296. return false;
  297. }
  298. return new Date( wp.api.utils.parseISO8601( theISODate ) );
  299. }
  300. },
  301. /**
  302. * Build a helper function to retrieve related model.
  303. *
  304. * @param {string} parentModel The parent model.
  305. * @param {int} modelId The model ID if the object to request
  306. * @param {string} modelName The model name to use when constructing the model.
  307. * @param {string} embedSourcePoint Where to check the embedds object for _embed data.
  308. * @param {string} embedCheckField Which model field to check to see if the model has data.
  309. *
  310. * @return {Deferred.promise} A promise which resolves to the constructed model.
  311. */
  312. buildModelGetter = function( parentModel, modelId, modelName, embedSourcePoint, embedCheckField ) {
  313. var getModel, embeddeds, attributes, deferred;
  314. deferred = jQuery.Deferred();
  315. embeddeds = parentModel.get( '_embedded' ) || {};
  316. // Verify that we have a valid object id.
  317. if ( ! _.isNumber( modelId ) || 0 === modelId ) {
  318. deferred.reject();
  319. return deferred;
  320. }
  321. // If we have embedded object data, use that when constructing the getModel.
  322. if ( embeddeds[ embedSourcePoint ] ) {
  323. attributes = _.findWhere( embeddeds[ embedSourcePoint ], { id: modelId } );
  324. }
  325. // Otherwise use the modelId.
  326. if ( ! attributes ) {
  327. attributes = { id: modelId };
  328. }
  329. // Create the new getModel model.
  330. getModel = new wp.api.models[ modelName ]( attributes );
  331. if ( ! getModel.get( embedCheckField ) ) {
  332. getModel.fetch( {
  333. success: function( getModel ) {
  334. deferred.resolve( getModel );
  335. },
  336. error: function( getModel, response ) {
  337. deferred.reject( response );
  338. }
  339. } );
  340. } else {
  341. // Resolve with the embedded model.
  342. deferred.resolve( getModel );
  343. }
  344. // Return a promise.
  345. return deferred.promise();
  346. },
  347. /**
  348. * Build a helper to retrieve a collection.
  349. *
  350. * @param {string} parentModel The parent model.
  351. * @param {string} collectionName The name to use when constructing the collection.
  352. * @param {string} embedSourcePoint Where to check the embedds object for _embed data.
  353. * @param {string} embedIndex An addiitonal optional index for the _embed data.
  354. *
  355. * @return {Deferred.promise} A promise which resolves to the constructed collection.
  356. */
  357. buildCollectionGetter = function( parentModel, collectionName, embedSourcePoint, embedIndex ) {
  358. /**
  359. * Returns a promise that resolves to the requested collection
  360. *
  361. * Uses the embedded data if available, otherwises fetches the
  362. * data from the server.
  363. *
  364. * @return {Deferred.promise} promise Resolves to a wp.api.collections[ collectionName ]
  365. * collection.
  366. */
  367. var postId, embeddeds, getObjects,
  368. classProperties = '',
  369. properties = '',
  370. deferred = jQuery.Deferred();
  371. postId = parentModel.get( 'id' );
  372. embeddeds = parentModel.get( '_embedded' ) || {};
  373. // Verify that we have a valid post id.
  374. if ( ! _.isNumber( postId ) || 0 === postId ) {
  375. deferred.reject();
  376. return deferred;
  377. }
  378. // If we have embedded getObjects data, use that when constructing the getObjects.
  379. if ( ! _.isUndefined( embedSourcePoint ) && ! _.isUndefined( embeddeds[ embedSourcePoint ] ) ) {
  380. // Some embeds also include an index offset, check for that.
  381. if ( _.isUndefined( embedIndex ) ) {
  382. // Use the embed source point directly.
  383. properties = embeddeds[ embedSourcePoint ];
  384. } else {
  385. // Add the index to the embed source point.
  386. properties = embeddeds[ embedSourcePoint ][ embedIndex ];
  387. }
  388. } else {
  389. // Otherwise use the postId.
  390. classProperties = { parent: postId };
  391. }
  392. // Create the new getObjects collection.
  393. getObjects = new wp.api.collections[ collectionName ]( properties, classProperties );
  394. // If we didn’t have embedded getObjects, fetch the getObjects data.
  395. if ( _.isUndefined( getObjects.models[0] ) ) {
  396. getObjects.fetch( {
  397. success: function( getObjects ) {
  398. // Add a helper 'parent_post' attribute onto the model.
  399. setHelperParentPost( getObjects, postId );
  400. deferred.resolve( getObjects );
  401. },
  402. error: function( getModel, response ) {
  403. deferred.reject( response );
  404. }
  405. } );
  406. } else {
  407. // Add a helper 'parent_post' attribute onto the model.
  408. setHelperParentPost( getObjects, postId );
  409. deferred.resolve( getObjects );
  410. }
  411. // Return a promise.
  412. return deferred.promise();
  413. },
  414. /**
  415. * Set the model post parent.
  416. */
  417. setHelperParentPost = function( collection, postId ) {
  418. // Attach post_parent id to the collection.
  419. _.each( collection.models, function( model ) {
  420. model.set( 'parent_post', postId );
  421. } );
  422. },
  423. /**
  424. * Add a helper function to handle post Meta.
  425. */
  426. MetaMixin = {
  427. /**
  428. * Get meta by key for a post.
  429. *
  430. * @param {string} key The meta key.
  431. *
  432. * @return {object} The post meta value.
  433. */
  434. getMeta: function( key ) {
  435. var metas = this.get( 'meta' );
  436. return metas[ key ];
  437. },
  438. /**
  439. * Get all meta key/values for a post.
  440. *
  441. * @return {object} The post metas, as a key value pair object.
  442. */
  443. getMetas: function() {
  444. return this.get( 'meta' );
  445. },
  446. /**
  447. * Set a group of meta key/values for a post.
  448. *
  449. * @param {object} meta The post meta to set, as key/value pairs.
  450. */
  451. setMetas: function( meta ) {
  452. var metas = this.get( 'meta' );
  453. _.extend( metas, meta );
  454. this.set( 'meta', metas );
  455. },
  456. /**
  457. * Set a single meta value for a post, by key.
  458. *
  459. * @param {string} key The meta key.
  460. * @param {object} value The meta value.
  461. */
  462. setMeta: function( key, value ) {
  463. var metas = this.get( 'meta' );
  464. metas[ key ] = value;
  465. this.set( 'meta', metas );
  466. }
  467. },
  468. /**
  469. * Add a helper function to handle post Revisions.
  470. */
  471. RevisionsMixin = {
  472. getRevisions: function() {
  473. return buildCollectionGetter( this, 'PostRevisions' );
  474. }
  475. },
  476. /**
  477. * Add a helper function to handle post Tags.
  478. */
  479. TagsMixin = {
  480. /**
  481. * Get the tags for a post.
  482. *
  483. * @return {Deferred.promise} promise Resolves to an array of tags.
  484. */
  485. getTags: function() {
  486. var tagIds = this.get( 'tags' ),
  487. tags = new wp.api.collections.Tags();
  488. // Resolve with an empty array if no tags.
  489. if ( _.isEmpty( tagIds ) ) {
  490. return jQuery.Deferred().resolve( [] );
  491. }
  492. return tags.fetch( { data: { include: tagIds } } );
  493. },
  494. /**
  495. * Set the tags for a post.
  496. *
  497. * Accepts an array of tag slugs, or a Tags collection.
  498. *
  499. * @param {array|Backbone.Collection} tags The tags to set on the post.
  500. *
  501. */
  502. setTags: function( tags ) {
  503. var allTags, newTag,
  504. self = this,
  505. newTags = [];
  506. if ( _.isString( tags ) ) {
  507. return false;
  508. }
  509. // If this is an array of slugs, build a collection.
  510. if ( _.isArray( tags ) ) {
  511. // Get all the tags.
  512. allTags = new wp.api.collections.Tags();
  513. allTags.fetch( {
  514. data: { per_page: 100 },
  515. success: function( alltags ) {
  516. // Find the passed tags and set them up.
  517. _.each( tags, function( tag ) {
  518. newTag = new wp.api.models.Tag( alltags.findWhere( { slug: tag } ) );
  519. // Tie the new tag to the post.
  520. newTag.set( 'parent_post', self.get( 'id' ) );
  521. // Add the new tag to the collection.
  522. newTags.push( newTag );
  523. } );
  524. tags = new wp.api.collections.Tags( newTags );
  525. self.setTagsWithCollection( tags );
  526. }
  527. } );
  528. } else {
  529. this.setTagsWithCollection( tags );
  530. }
  531. },
  532. /**
  533. * Set the tags for a post.
  534. *
  535. * Accepts a Tags collection.
  536. *
  537. * @param {array|Backbone.Collection} tags The tags to set on the post.
  538. *
  539. */
  540. setTagsWithCollection: function( tags ) {
  541. // Pluck out the category ids.
  542. this.set( 'tags', tags.pluck( 'id' ) );
  543. return this.save();
  544. }
  545. },
  546. /**
  547. * Add a helper function to handle post Categories.
  548. */
  549. CategoriesMixin = {
  550. /**
  551. * Get a the categories for a post.
  552. *
  553. * @return {Deferred.promise} promise Resolves to an array of categories.
  554. */
  555. getCategories: function() {
  556. var categoryIds = this.get( 'categories' ),
  557. categories = new wp.api.collections.Categories();
  558. // Resolve with an empty array if no categories.
  559. if ( _.isEmpty( categoryIds ) ) {
  560. return jQuery.Deferred().resolve( [] );
  561. }
  562. return categories.fetch( { data: { include: categoryIds } } );
  563. },
  564. /**
  565. * Set the categories for a post.
  566. *
  567. * Accepts an array of category slugs, or a Categories collection.
  568. *
  569. * @param {array|Backbone.Collection} categories The categories to set on the post.
  570. *
  571. */
  572. setCategories: function( categories ) {
  573. var allCategories, newCategory,
  574. self = this,
  575. newCategories = [];
  576. if ( _.isString( categories ) ) {
  577. return false;
  578. }
  579. // If this is an array of slugs, build a collection.
  580. if ( _.isArray( categories ) ) {
  581. // Get all the categories.
  582. allCategories = new wp.api.collections.Categories();
  583. allCategories.fetch( {
  584. data: { per_page: 100 },
  585. success: function( allcats ) {
  586. // Find the passed categories and set them up.
  587. _.each( categories, function( category ) {
  588. newCategory = new wp.api.models.Category( allcats.findWhere( { slug: category } ) );
  589. // Tie the new category to the post.
  590. newCategory.set( 'parent_post', self.get( 'id' ) );
  591. // Add the new category to the collection.
  592. newCategories.push( newCategory );
  593. } );
  594. categories = new wp.api.collections.Categories( newCategories );
  595. self.setCategoriesWithCollection( categories );
  596. }
  597. } );
  598. } else {
  599. this.setCategoriesWithCollection( categories );
  600. }
  601. },
  602. /**
  603. * Set the categories for a post.
  604. *
  605. * Accepts Categories collection.
  606. *
  607. * @param {array|Backbone.Collection} categories The categories to set on the post.
  608. *
  609. */
  610. setCategoriesWithCollection: function( categories ) {
  611. // Pluck out the category ids.
  612. this.set( 'categories', categories.pluck( 'id' ) );
  613. return this.save();
  614. }
  615. },
  616. /**
  617. * Add a helper function to retrieve the author user model.
  618. */
  619. AuthorMixin = {
  620. getAuthorUser: function() {
  621. return buildModelGetter( this, this.get( 'author' ), 'User', 'author', 'name' );
  622. }
  623. },
  624. /**
  625. * Add a helper function to retrieve the featured media.
  626. */
  627. FeaturedMediaMixin = {
  628. getFeaturedMedia: function() {
  629. return buildModelGetter( this, this.get( 'featured_media' ), 'Media', 'wp:featuredmedia', 'source_url' );
  630. }
  631. };
  632. // Exit if we don't have valid model defaults.
  633. if ( _.isUndefined( model.prototype.args ) ) {
  634. return model;
  635. }
  636. // Go thru the parsable date fields, if our model contains any of them it gets the TimeStampedMixin.
  637. _.each( parseableDates, function( theDateKey ) {
  638. if ( ! _.isUndefined( model.prototype.args[ theDateKey ] ) ) {
  639. hasDate = true;
  640. }
  641. } );
  642. // Add the TimeStampedMixin for models that contain a date field.
  643. if ( hasDate ) {
  644. model = model.extend( TimeStampedMixin );
  645. }
  646. // Add the AuthorMixin for models that contain an author.
  647. if ( ! _.isUndefined( model.prototype.args.author ) ) {
  648. model = model.extend( AuthorMixin );
  649. }
  650. // Add the FeaturedMediaMixin for models that contain a featured_media.
  651. if ( ! _.isUndefined( model.prototype.args.featured_media ) ) {
  652. model = model.extend( FeaturedMediaMixin );
  653. }
  654. // Add the CategoriesMixin for models that support categories collections.
  655. if ( ! _.isUndefined( model.prototype.args.categories ) ) {
  656. model = model.extend( CategoriesMixin );
  657. }
  658. // Add the MetaMixin for models that support meta.
  659. if ( ! _.isUndefined( model.prototype.args.meta ) ) {
  660. model = model.extend( MetaMixin );
  661. }
  662. // Add the TagsMixin for models that support tags collections.
  663. if ( ! _.isUndefined( model.prototype.args.tags ) ) {
  664. model = model.extend( TagsMixin );
  665. }
  666. // Add the RevisionsMixin for models that support revisions collections.
  667. if ( ! _.isUndefined( loadingObjects.collections[ modelClassName + 'Revisions' ] ) ) {
  668. model = model.extend( RevisionsMixin );
  669. }
  670. return model;
  671. };
  672. })( window );
  673. /* global wpApiSettings:false */
  674. // Suppress warning about parse function's unused "options" argument:
  675. /* jshint unused:false */
  676. (function() {
  677. 'use strict';
  678. var wpApiSettings = window.wpApiSettings || {},
  679. trashableTypes = [ 'Comment', 'Media', 'Comment', 'Post', 'Page', 'Status', 'Taxonomy', 'Type' ];
  680. /**
  681. * Backbone base model for all models.
  682. */
  683. wp.api.WPApiBaseModel = Backbone.Model.extend(
  684. /** @lends WPApiBaseModel.prototype */
  685. {
  686. // Initialize the model.
  687. initialize: function() {
  688. /**
  689. * Types that don't support trashing require passing ?force=true to delete.
  690. *
  691. */
  692. if ( -1 === _.indexOf( trashableTypes, this.name ) ) {
  693. this.requireForceForDelete = true;
  694. }
  695. },
  696. /**
  697. * Set nonce header before every Backbone sync.
  698. *
  699. * @param {string} method.
  700. * @param {Backbone.Model} model.
  701. * @param {{beforeSend}, *} options.
  702. * @return {*}.
  703. */
  704. sync: function( method, model, options ) {
  705. var beforeSend;
  706. options = options || {};
  707. // Remove date_gmt if null.
  708. if ( _.isNull( model.get( 'date_gmt' ) ) ) {
  709. model.unset( 'date_gmt' );
  710. }
  711. // Remove slug if empty.
  712. if ( _.isEmpty( model.get( 'slug' ) ) ) {
  713. model.unset( 'slug' );
  714. }
  715. if ( _.isFunction( model.nonce ) && ! _.isEmpty( model.nonce() ) ) {
  716. beforeSend = options.beforeSend;
  717. // @todo Enable option for jsonp endpoints.
  718. // options.dataType = 'jsonp';
  719. // Include the nonce with requests.
  720. options.beforeSend = function( xhr ) {
  721. xhr.setRequestHeader( 'X-WP-Nonce', model.nonce() );
  722. if ( beforeSend ) {
  723. return beforeSend.apply( this, arguments );
  724. }
  725. };
  726. // Update the nonce when a new nonce is returned with the response.
  727. options.complete = function( xhr ) {
  728. var returnedNonce = xhr.getResponseHeader( 'X-WP-Nonce' );
  729. if ( returnedNonce && _.isFunction( model.nonce ) && model.nonce() !== returnedNonce ) {
  730. model.endpointModel.set( 'nonce', returnedNonce );
  731. }
  732. };
  733. }
  734. // Add '?force=true' to use delete method when required.
  735. if ( this.requireForceForDelete && 'delete' === method ) {
  736. model.url = model.url() + '?force=true';
  737. }
  738. return Backbone.sync( method, model, options );
  739. },
  740. /**
  741. * Save is only allowed when the PUT OR POST methods are available for the endpoint.
  742. */
  743. save: function( attrs, options ) {
  744. // Do we have the put method, then execute the save.
  745. if ( _.includes( this.methods, 'PUT' ) || _.includes( this.methods, 'POST' ) ) {
  746. // Proxy the call to the original save function.
  747. return Backbone.Model.prototype.save.call( this, attrs, options );
  748. } else {
  749. // Otherwise bail, disallowing action.
  750. return false;
  751. }
  752. },
  753. /**
  754. * Delete is only allowed when the DELETE method is available for the endpoint.
  755. */
  756. destroy: function( options ) {
  757. // Do we have the DELETE method, then execute the destroy.
  758. if ( _.includes( this.methods, 'DELETE' ) ) {
  759. // Proxy the call to the original save function.
  760. return Backbone.Model.prototype.destroy.call( this, options );
  761. } else {
  762. // Otherwise bail, disallowing action.
  763. return false;
  764. }
  765. }
  766. }
  767. );
  768. /**
  769. * API Schema model. Contains meta information about the API.
  770. */
  771. wp.api.models.Schema = wp.api.WPApiBaseModel.extend(
  772. /** @lends Schema.prototype */
  773. {
  774. defaults: {
  775. _links: {},
  776. namespace: null,
  777. routes: {}
  778. },
  779. initialize: function( attributes, options ) {
  780. var model = this;
  781. options = options || {};
  782. wp.api.WPApiBaseModel.prototype.initialize.call( model, attributes, options );
  783. model.apiRoot = options.apiRoot || wpApiSettings.root;
  784. model.versionString = options.versionString || wpApiSettings.versionString;
  785. },
  786. url: function() {
  787. return this.apiRoot + this.versionString;
  788. }
  789. }
  790. );
  791. })();
  792. ( function() {
  793. 'use strict';
  794. var wpApiSettings = window.wpApiSettings || {};
  795. /**
  796. * Contains basic collection functionality such as pagination.
  797. */
  798. wp.api.WPApiBaseCollection = Backbone.Collection.extend(
  799. /** @lends BaseCollection.prototype */
  800. {
  801. /**
  802. * Setup default state.
  803. */
  804. initialize: function( models, options ) {
  805. this.state = {
  806. data: {},
  807. currentPage: null,
  808. totalPages: null,
  809. totalObjects: null
  810. };
  811. if ( _.isUndefined( options ) ) {
  812. this.parent = '';
  813. } else {
  814. this.parent = options.parent;
  815. }
  816. },
  817. /**
  818. * Extend Backbone.Collection.sync to add nince and pagination support.
  819. *
  820. * Set nonce header before every Backbone sync.
  821. *
  822. * @param {string} method.
  823. * @param {Backbone.Model} model.
  824. * @param {{success}, *} options.
  825. * @return {*}.
  826. */
  827. sync: function( method, model, options ) {
  828. var beforeSend, success,
  829. self = this;
  830. options = options || {};
  831. if ( _.isFunction( model.nonce ) && ! _.isEmpty( model.nonce() ) ) {
  832. beforeSend = options.beforeSend;
  833. // Include the nonce with requests.
  834. options.beforeSend = function( xhr ) {
  835. xhr.setRequestHeader( 'X-WP-Nonce', model.nonce() );
  836. if ( beforeSend ) {
  837. return beforeSend.apply( self, arguments );
  838. }
  839. };
  840. // Update the nonce when a new nonce is returned with the response.
  841. options.complete = function( xhr ) {
  842. var returnedNonce = xhr.getResponseHeader( 'X-WP-Nonce' );
  843. if ( returnedNonce && _.isFunction( model.nonce ) && model.nonce() !== returnedNonce ) {
  844. model.endpointModel.set( 'nonce', returnedNonce );
  845. }
  846. };
  847. }
  848. // When reading, add pagination data.
  849. if ( 'read' === method ) {
  850. if ( options.data ) {
  851. self.state.data = _.clone( options.data );
  852. delete self.state.data.page;
  853. } else {
  854. self.state.data = options.data = {};
  855. }
  856. if ( 'undefined' === typeof options.data.page ) {
  857. self.state.currentPage = null;
  858. self.state.totalPages = null;
  859. self.state.totalObjects = null;
  860. } else {
  861. self.state.currentPage = options.data.page - 1;
  862. }
  863. success = options.success;
  864. options.success = function( data, textStatus, request ) {
  865. if ( ! _.isUndefined( request ) ) {
  866. self.state.totalPages = parseInt( request.getResponseHeader( 'x-wp-totalpages' ), 10 );
  867. self.state.totalObjects = parseInt( request.getResponseHeader( 'x-wp-total' ), 10 );
  868. }
  869. if ( null === self.state.currentPage ) {
  870. self.state.currentPage = 1;
  871. } else {
  872. self.state.currentPage++;
  873. }
  874. if ( success ) {
  875. return success.apply( this, arguments );
  876. }
  877. };
  878. }
  879. // Continue by calling Bacckbone's sync.
  880. return Backbone.sync( method, model, options );
  881. },
  882. /**
  883. * Fetches the next page of objects if a new page exists.
  884. *
  885. * @param {data: {page}} options.
  886. * @return {*}.
  887. */
  888. more: function( options ) {
  889. options = options || {};
  890. options.data = options.data || {};
  891. _.extend( options.data, this.state.data );
  892. if ( 'undefined' === typeof options.data.page ) {
  893. if ( ! this.hasMore() ) {
  894. return false;
  895. }
  896. if ( null === this.state.currentPage || this.state.currentPage <= 1 ) {
  897. options.data.page = 2;
  898. } else {
  899. options.data.page = this.state.currentPage + 1;
  900. }
  901. }
  902. return this.fetch( options );
  903. },
  904. /**
  905. * Returns true if there are more pages of objects available.
  906. *
  907. * @return {null|boolean}
  908. */
  909. hasMore: function() {
  910. if ( null === this.state.totalPages ||
  911. null === this.state.totalObjects ||
  912. null === this.state.currentPage ) {
  913. return null;
  914. } else {
  915. return ( this.state.currentPage < this.state.totalPages );
  916. }
  917. }
  918. }
  919. );
  920. } )();
  921. ( function() {
  922. 'use strict';
  923. var Endpoint, initializedDeferreds = {},
  924. wpApiSettings = window.wpApiSettings || {};
  925. /** @namespace wp */
  926. window.wp = window.wp || {};
  927. /** @namespace wp.api */
  928. wp.api = wp.api || {};
  929. // If wpApiSettings is unavailable, try the default.
  930. if ( _.isEmpty( wpApiSettings ) ) {
  931. wpApiSettings.root = window.location.origin + '/wp-json/';
  932. }
  933. Endpoint = Backbone.Model.extend(/** @lends Endpoint.prototype */{
  934. defaults: {
  935. apiRoot: wpApiSettings.root,
  936. versionString: wp.api.versionString,
  937. nonce: null,
  938. schema: null,
  939. models: {},
  940. collections: {}
  941. },
  942. /**
  943. * Initialize the Endpoint model.
  944. */
  945. initialize: function() {
  946. var model = this, deferred;
  947. Backbone.Model.prototype.initialize.apply( model, arguments );
  948. deferred = jQuery.Deferred();
  949. model.schemaConstructed = deferred.promise();
  950. model.schemaModel = new wp.api.models.Schema( null, {
  951. apiRoot: model.get( 'apiRoot' ),
  952. versionString: model.get( 'versionString' ),
  953. nonce: model.get( 'nonce' )
  954. } );
  955. // When the model loads, resolve the promise.
  956. model.schemaModel.once( 'change', function() {
  957. model.constructFromSchema();
  958. deferred.resolve( model );
  959. } );
  960. if ( model.get( 'schema' ) ) {
  961. // Use schema supplied as model attribute.
  962. model.schemaModel.set( model.schemaModel.parse( model.get( 'schema' ) ) );
  963. } else if (
  964. ! _.isUndefined( sessionStorage ) &&
  965. ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) &&
  966. sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) )
  967. ) {
  968. // Used a cached copy of the schema model if available.
  969. model.schemaModel.set( model.schemaModel.parse( JSON.parse( sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) ) ) ) );
  970. } else {
  971. model.schemaModel.fetch( {
  972. /**
  973. * When the server returns the schema model data, store the data in a sessionCache so we don't
  974. * have to retrieve it again for this session. Then, construct the models and collections based
  975. * on the schema model data.
  976. *
  977. * @ignore
  978. */
  979. success: function( newSchemaModel ) {
  980. // Store a copy of the schema model in the session cache if available.
  981. if ( ! _.isUndefined( sessionStorage ) && ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) ) {
  982. try {
  983. sessionStorage.setItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ), JSON.stringify( newSchemaModel ) );
  984. } catch ( error ) {
  985. // Fail silently, fixes errors in safari private mode.
  986. }
  987. }
  988. },
  989. // Log the error condition.
  990. error: function( err ) {
  991. window.console.log( err );
  992. }
  993. } );
  994. }
  995. },
  996. constructFromSchema: function() {
  997. var routeModel = this, modelRoutes, collectionRoutes, schemaRoot, loadingObjects,
  998. /**
  999. * Set up the model and collection name mapping options. As the schema is built, the
  1000. * model and collection names will be adjusted if they are found in the mapping object.
  1001. *
  1002. * Localizing a variable wpApiSettings.mapping will over-ride the default mapping options.
  1003. *
  1004. */
  1005. mapping = wpApiSettings.mapping || {
  1006. models: {
  1007. 'Categories': 'Category',
  1008. 'Comments': 'Comment',
  1009. 'Pages': 'Page',
  1010. 'PagesMeta': 'PageMeta',
  1011. 'PagesRevisions': 'PageRevision',
  1012. 'Posts': 'Post',
  1013. 'PostsCategories': 'PostCategory',
  1014. 'PostsRevisions': 'PostRevision',
  1015. 'PostsTags': 'PostTag',
  1016. 'Schema': 'Schema',
  1017. 'Statuses': 'Status',
  1018. 'Tags': 'Tag',
  1019. 'Taxonomies': 'Taxonomy',
  1020. 'Types': 'Type',
  1021. 'Users': 'User'
  1022. },
  1023. collections: {
  1024. 'PagesMeta': 'PageMeta',
  1025. 'PagesRevisions': 'PageRevisions',
  1026. 'PostsCategories': 'PostCategories',
  1027. 'PostsMeta': 'PostMeta',
  1028. 'PostsRevisions': 'PostRevisions',
  1029. 'PostsTags': 'PostTags'
  1030. }
  1031. },
  1032. modelEndpoints = routeModel.get( 'modelEndpoints' ),
  1033. modelRegex = new RegExp( '(?:.*[+)]|\/(' + modelEndpoints.join( '|' ) + '))$' );
  1034. /**
  1035. * Iterate thru the routes, picking up models and collections to build. Builds two arrays,
  1036. * one for models and one for collections.
  1037. */
  1038. modelRoutes = [];
  1039. collectionRoutes = [];
  1040. schemaRoot = routeModel.get( 'apiRoot' ).replace( wp.api.utils.getRootUrl(), '' );
  1041. loadingObjects = {};
  1042. /**
  1043. * Tracking objects for models and collections.
  1044. */
  1045. loadingObjects.models = {};
  1046. loadingObjects.collections = {};
  1047. _.each( routeModel.schemaModel.get( 'routes' ), function( route, index ) {
  1048. // Skip the schema root if included in the schema.
  1049. if ( index !== routeModel.get( ' versionString' ) &&
  1050. index !== schemaRoot &&
  1051. index !== ( '/' + routeModel.get( 'versionString' ).slice( 0, -1 ) )
  1052. ) {
  1053. // Single items end with a regex, or a special case word.
  1054. if ( modelRegex.test( index ) ) {
  1055. modelRoutes.push( { index: index, route: route } );
  1056. } else {
  1057. // Collections end in a name.
  1058. collectionRoutes.push( { index: index, route: route } );
  1059. }
  1060. }
  1061. } );
  1062. /**
  1063. * Construct the models.
  1064. *
  1065. * Base the class name on the route endpoint.
  1066. */
  1067. _.each( modelRoutes, function( modelRoute ) {
  1068. // Extract the name and any parent from the route.
  1069. var modelClassName,
  1070. routeName = wp.api.utils.extractRoutePart( modelRoute.index, 2, routeModel.get( 'versionString' ), true ),
  1071. parentName = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), false ),
  1072. routeEnd = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), true );
  1073. // Clear the parent part of the rouite if its actually the version string.
  1074. if ( parentName === routeModel.get( 'versionString' ) ) {
  1075. parentName = '';
  1076. }
  1077. // Handle the special case of the 'me' route.
  1078. if ( 'me' === routeEnd ) {
  1079. routeName = 'me';
  1080. }
  1081. // If the model has a parent in its route, add that to its class name.
  1082. if ( '' !== parentName && parentName !== routeName ) {
  1083. modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1084. modelClassName = mapping.models[ modelClassName ] || modelClassName;
  1085. loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
  1086. // Return a constructed url based on the parent and id.
  1087. url: function() {
  1088. var url =
  1089. routeModel.get( 'apiRoot' ) +
  1090. routeModel.get( 'versionString' ) +
  1091. parentName + '/' +
  1092. ( ( _.isUndefined( this.get( 'parent' ) ) || 0 === this.get( 'parent' ) ) ?
  1093. ( _.isUndefined( this.get( 'parent_post' ) ) ? '' : this.get( 'parent_post' ) + '/' ) :
  1094. this.get( 'parent' ) + '/' ) +
  1095. routeName;
  1096. if ( ! _.isUndefined( this.get( 'id' ) ) ) {
  1097. url += '/' + this.get( 'id' );
  1098. }
  1099. return url;
  1100. },
  1101. // Track nonces on the Endpoint 'routeModel'.
  1102. nonce: function() {
  1103. return routeModel.get( 'nonce' );
  1104. },
  1105. endpointModel: routeModel,
  1106. // Include a reference to the original route object.
  1107. route: modelRoute,
  1108. // Include a reference to the original class name.
  1109. name: modelClassName,
  1110. // Include the array of route methods for easy reference.
  1111. methods: modelRoute.route.methods,
  1112. // Include the array of route endpoints for easy reference.
  1113. endpoints: modelRoute.route.endpoints
  1114. } );
  1115. } else {
  1116. // This is a model without a parent in its route.
  1117. modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1118. modelClassName = mapping.models[ modelClassName ] || modelClassName;
  1119. loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
  1120. // Function that returns a constructed url based on the id.
  1121. url: function() {
  1122. var url = routeModel.get( 'apiRoot' ) +
  1123. routeModel.get( 'versionString' ) +
  1124. ( ( 'me' === routeName ) ? 'users/me' : routeName );
  1125. if ( ! _.isUndefined( this.get( 'id' ) ) ) {
  1126. url += '/' + this.get( 'id' );
  1127. }
  1128. return url;
  1129. },
  1130. // Track nonces at the Endpoint level.
  1131. nonce: function() {
  1132. return routeModel.get( 'nonce' );
  1133. },
  1134. endpointModel: routeModel,
  1135. // Include a reference to the original route object.
  1136. route: modelRoute,
  1137. // Include a reference to the original class name.
  1138. name: modelClassName,
  1139. // Include the array of route methods for easy reference.
  1140. methods: modelRoute.route.methods,
  1141. // Include the array of route endpoints for easy reference.
  1142. endpoints: modelRoute.route.endpoints
  1143. } );
  1144. }
  1145. // Add defaults to the new model, pulled form the endpoint.
  1146. wp.api.utils.decorateFromRoute(
  1147. modelRoute.route.endpoints,
  1148. loadingObjects.models[ modelClassName ],
  1149. routeModel.get( 'versionString' )
  1150. );
  1151. } );
  1152. /**
  1153. * Construct the collections.
  1154. *
  1155. * Base the class name on the route endpoint.
  1156. */
  1157. _.each( collectionRoutes, function( collectionRoute ) {
  1158. // Extract the name and any parent from the route.
  1159. var collectionClassName, modelClassName,
  1160. routeName = collectionRoute.index.slice( collectionRoute.index.lastIndexOf( '/' ) + 1 ),
  1161. parentName = wp.api.utils.extractRoutePart( collectionRoute.index, 1, routeModel.get( 'versionString' ), false );
  1162. // If the collection has a parent in its route, add that to its class name.
  1163. if ( '' !== parentName && parentName !== routeName && routeModel.get( 'versionString' ) !== parentName ) {
  1164. collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1165. modelClassName = mapping.models[ collectionClassName ] || collectionClassName;
  1166. collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
  1167. loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
  1168. // Function that returns a constructed url passed on the parent.
  1169. url: function() {
  1170. return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) +
  1171. parentName + '/' + this.parent + '/' +
  1172. routeName;
  1173. },
  1174. // Specify the model that this collection contains.
  1175. model: function( attrs, options ) {
  1176. return new loadingObjects.models[ modelClassName ]( attrs, options );
  1177. },
  1178. // Track nonces at the Endpoint level.
  1179. nonce: function() {
  1180. return routeModel.get( 'nonce' );
  1181. },
  1182. endpointModel: routeModel,
  1183. // Include a reference to the original class name.
  1184. name: collectionClassName,
  1185. // Include a reference to the original route object.
  1186. route: collectionRoute,
  1187. // Include the array of route methods for easy reference.
  1188. methods: collectionRoute.route.methods
  1189. } );
  1190. } else {
  1191. // This is a collection without a parent in its route.
  1192. collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1193. modelClassName = mapping.models[ collectionClassName ] || collectionClassName;
  1194. collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
  1195. loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
  1196. // For the url of a root level collection, use a string.
  1197. url: function() {
  1198. return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) + routeName;
  1199. },
  1200. // Specify the model that this collection contains.
  1201. model: function( attrs, options ) {
  1202. return new loadingObjects.models[ modelClassName ]( attrs, options );
  1203. },
  1204. // Track nonces at the Endpoint level.
  1205. nonce: function() {
  1206. return routeModel.get( 'nonce' );
  1207. },
  1208. endpointModel: routeModel,
  1209. // Include a reference to the original class name.
  1210. name: collectionClassName,
  1211. // Include a reference to the original route object.
  1212. route: collectionRoute,
  1213. // Include the array of route methods for easy reference.
  1214. methods: collectionRoute.route.methods
  1215. } );
  1216. }
  1217. // Add defaults to the new model, pulled form the endpoint.
  1218. wp.api.utils.decorateFromRoute( collectionRoute.route.endpoints, loadingObjects.collections[ collectionClassName ] );
  1219. } );
  1220. // Add mixins and helpers for each of the models.
  1221. _.each( loadingObjects.models, function( model, index ) {
  1222. loadingObjects.models[ index ] = wp.api.utils.addMixinsAndHelpers( model, index, loadingObjects );
  1223. } );
  1224. // Set the routeModel models and collections.
  1225. routeModel.set( 'models', loadingObjects.models );
  1226. routeModel.set( 'collections', loadingObjects.collections );
  1227. }
  1228. } );
  1229. wp.api.endpoints = new Backbone.Collection();
  1230. /**
  1231. * Initialize the wp-api, optionally passing the API root.
  1232. *
  1233. * @param {object} [args]
  1234. * @param {string} [args.nonce] The nonce. Optional, defaults to wpApiSettings.nonce.
  1235. * @param {string} [args.apiRoot] The api root. Optional, defaults to wpApiSettings.root.
  1236. * @param {string} [args.versionString] The version string. Optional, defaults to wpApiSettings.root.
  1237. * @param {object} [args.schema] The schema. Optional, will be fetched from API if not provided.
  1238. */
  1239. wp.api.init = function( args ) {
  1240. var endpoint, attributes = {}, deferred, promise;
  1241. args = args || {};
  1242. attributes.nonce = _.isString( args.nonce ) ? args.nonce : ( wpApiSettings.nonce || '' );
  1243. attributes.apiRoot = args.apiRoot || wpApiSettings.root || '/wp-json';
  1244. attributes.versionString = args.versionString || wpApiSettings.versionString || 'wp/v2/';
  1245. attributes.schema = args.schema || null;
  1246. attributes.modelEndpoints = args.modelEndpoints || [ 'me', 'settings' ];
  1247. if ( ! attributes.schema && attributes.apiRoot === wpApiSettings.root && attributes.versionString === wpApiSettings.versionString ) {
  1248. attributes.schema = wpApiSettings.schema;
  1249. }
  1250. if ( ! initializedDeferreds[ attributes.apiRoot + attributes.versionString ] ) {
  1251. // Look for an existing copy of this endpoint.
  1252. endpoint = wp.api.endpoints.findWhere( { 'apiRoot': attributes.apiRoot, 'versionString': attributes.versionString } );
  1253. if ( ! endpoint ) {
  1254. endpoint = new Endpoint( attributes );
  1255. }
  1256. deferred = jQuery.Deferred();
  1257. promise = deferred.promise();
  1258. endpoint.schemaConstructed.done( function( resolvedEndpoint ) {
  1259. wp.api.endpoints.add( resolvedEndpoint );
  1260. // Map the default endpoints, extending any already present items (including Schema model).
  1261. wp.api.models = _.extend( wp.api.models, resolvedEndpoint.get( 'models' ) );
  1262. wp.api.collections = _.extend( wp.api.collections, resolvedEndpoint.get( 'collections' ) );
  1263. deferred.resolve( resolvedEndpoint );
  1264. } );
  1265. initializedDeferreds[ attributes.apiRoot + attributes.versionString ] = promise;
  1266. }
  1267. return initializedDeferreds[ attributes.apiRoot + attributes.versionString ];
  1268. };
  1269. /**
  1270. * Construct the default endpoints and add to an endpoints collection.
  1271. */
  1272. // The wp.api.init function returns a promise that will resolve with the endpoint once it is ready.
  1273. wp.api.loadPromise = wp.api.init();
  1274. } )();