Search code examples
ember.jsember-dataember-cli

Custom post-request with RESTAdapter


My models work with the server via Ember's default RESTAdapter.

I just created a custom endpoint /mail on my server which sends an e-mail if provided a name, valid e-mail-adress and text.

How do I make Ember send that custom post-request? Is it possible without Ember.ajax at all?


Solution

  • For me personally, I wouldn't use Ember-Data to handle that scenario; I generally only use Ember-Data to handle my persisted models. If you try to use Ember-Data for other AJAX calls, it's just going to become a mess. Remember that Ember-Data's job is to manage your persisted data and one way that it can do that is with AJAX calls. That doesn't mean that anything that requires an AJAX call should be handled with Ember-Data.

    I have this same issue and I wrote a utility module that has functions for all of my non-model AJAX stuff. This makes it really easy to swap out for testing. Here's a small example:

    // utils/ajax.js
    
    export function sendHelpEmail(comment) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'POST',
                url: '/api/contact_us',
                contentType: 'application/json',
                data: JSON.stringify({ comment }),
                processData: false,
                statusCode: {
                    200: () => Em.run(null, resolve),
                    500: () => Em.run(null, reject)
                }
            });
        });
    }
    

    Then, I can do something like this in my controller:

    import { sendHelpEmail} from '../utils/ajax.js';
    
    export default Em.Controller.extend({
        actions: {
            sendEmail() {
                sendHelpEmail(this.get('comment'));
            }
        }
    });