diff --git a/kolibri/core/assets/src/api_resource.js b/kolibri/core/assets/src/api_resource.js index e063330cd16..d6df4a43c6d 100644 --- a/kolibri/core/assets/src/api_resource.js +++ b/kolibri/core/assets/src/api_resource.js @@ -27,12 +27,31 @@ class Model { this.synced = false; // force IDs to always be strings - this should be changed on the server-side too - this.attributes[this.resource.idKey] = String(this.attributes[this.resource.idKey]); + if ('id' in data) { + this.attributes[this.resource.idKey] = String(this.attributes[this.resource.idKey]); + } // Keep track of any unresolved promises that have been generated by async methods of the Model this.promises = []; } + getCookie(name) { + let cookieValue = null; + if (document.cookie && document.cookie !== '') { + const cookies = document.cookie.split(';'); + for (let i = 0; i < cookies.length; i++) { + const cookie = cookies[i].trim(); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) === (name.concat('='))) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; + } + + /** * Method to fetch data from the server for this particular model. * @param {object} params - an object of parameters to be parsed into GET parameters on the @@ -100,18 +119,21 @@ class Model { } else { this.synced = false; let url; - let method; + let clientObj; if (this.id) { // If this Model has an id, then can do a PATCH against the Model url = this.url; - method = 'PATCH'; + clientObj = { path: url, method: 'PATCH' }; } else { // Otherwise, must POST to the Collection endpoint to create the Model url = this.resource.collectionUrl(); - method = 'POST'; + const csrftoken = this.getCookie('csrftoken'); + clientObj = { path: url, entity: payload, + headers: { 'Content-Type': 'application/json', + 'X-CSRFToken': csrftoken } }; } // Do a save on the URL. - client({ path: url, method }).then((response) => { + client(clientObj).then((response) => { const oldId = this.id; // Set the retrieved Object onto the Model instance. this.set(response.entity); @@ -121,8 +143,8 @@ class Model { } // Flag that the Model has been fetched. this.synced = true; - // Resolve the promise with the attributes of the Model. - resolve(this.attributes); + // Resolve the promise with the Model. + resolve(this); // Clean up the reference to this promise this.promises.splice(this.promises.indexOf(promise), 1); }, (response) => {