Skip to content

Instantly share code, notes, and snippets.

@spr1ne
Created August 11, 2016 18:03
Show Gist options
  • Save spr1ne/4396d8313f1f93dd6aee27be7c5a161c to your computer and use it in GitHub Desktop.
Save spr1ne/4396d8313f1f93dd6aee27be7c5a161c to your computer and use it in GitHub Desktop.
[Ember.js] Custom API request
import RESTAdapter from 'ember-data/adapters/rest';
export default RESTAdapter.extend({
/**
* @param {DS.Model} model
* @param {JSON} serializedCommentData
* @returns {*}
*/
postComment(model, serializedCommentData) {
// http://example.com/posts/5/comments
const url = this.buildURL('post', model.get('id')) + "/comments";
return this.ajax(url, 'POST', {
data: {
'comment': serializedCommentData
}
});
}
});
import Controller from 'ember-controller';
export default Controller.extend({
actions: {
submitForm(commentText) {
// Post model already there (from route)
var post = this.get('model');
post.createComment({ text: commentText }).then((commentRecord) => {
alert('Yahoo! Comment created');
});
}
}
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo } from 'ember-data/relationships';
export default Model.extend({
text: attr('string'),
post: belongsTo()
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';
/**
* For example, we have instance of 'post' model
* If we want create comment in this 'post', we do:
*
* post.createComment({
* text: 'example text of comment'
* });
*/
export default Model.extend({
title: attr('string'),
comments: hasMany(),
/**
* [POST] /posts/{id}/comments
*
* @param {JSON} rawData
* @returns {Promise}
*/
createComment(rawData) {
// this.constructor.modelName = 'post'
const adapter = this.store.adapterFor(this.constructor.modelName);
// Create record, and serialize before sending
const commentRecord = this.store.createRecord('comment', rawData);
let serializedCommentData = commentRecord.serialize();
// Make ajax request [POST]
return adapter.postComment(this, serializedCommentData).then((responseData) => {
let commentData = responseData.comment;
let commentSerializer = this.store.serializerFor('comment');
let CommentModel = this.store.modelFor('comment');
// Normalize response and set Data into commentRecord (what is created earlier)
commentSerializer.normalize(CommentModel, commentData, 'comment');
commentRecord.setProperties(commentData);
commentRecord.transitionTo('saved');
return commentRecord;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment