wp-api.js 46 KB

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