Skip to content

Discussion: Requests where there is no model eg. creating multiple #268

Description

@iezer

I'm working with an API that has a endpoint for creating multiple objects:

// Request
// POST /invitations
payload = { data: attributes { email: 'a@b.com,x@y.com' } }

// Response
data: [
 { id: '1', type: 'invitation', { attributes: { email: 'a@b.com' } } },
 { id: '2', type: 'invitation', { attributes: { email: 'x@y.com' } } }
]

With the recent changes to this addon I can actually implement this pretty easily:

// app/models/invitation.js
import DS from 'ember-data';
import { collectionAction, serializeAndPush } from 'ember-api-actions';

export default DS.Model.extend(
 email: DS.attr(),
 createMultiple: collectionAction({
    type: 'POST',
    urlType: 'createRecord',
    pushPayload: true,
    path: '',
    before(attributes) {
      return { data: { attributes } };
    },
    after: serializeAndPush
  }),

But to use it I have to temporarily create a record:

const newInvitation = this.store.createRecord('invitation');
newInvitation.createMultiple({ email: 'a@b.com,x@y.com' }).finally(() => {
  newInvitation.rollbackAttributes();
});

Not bad, but I'd love it if there was a way to attach this hook to the model class and not have to create the extra model.

// app/models/invitations.js
const InvitationModel = DS.Model.extend({
 email: DS.attr()
});

InvitationModel.reopenClass({
  createMultiple: collectionAction({
    type: 'POST',
    urlType: 'createRecord',
    pushPayload: true,
    path: '',
    before(attributes) {
      return { data: { attributes } };
    },
    after: serializeAndPush
  })
});

return InvitationModel;

I think this is possible but the issues are that the class doesn't have access to the container or the store, the factory does however, although I don't know if we want that to be the API.

Here are some options of what the API would look like. I think option 3 is the most viable. Thoughts?

// 1.
return store.modelFor('invitation').createMultiple({ email: 'a@b.com,x@y.com' });

// 2. The factory is a wrapper that knows about the class, store, and container, so it might be a good entry point.
return store.modelFactoryFor('invitation').createMultiple({ email: 'a@b.com,x@y.com' });

// 3.
return store.modelFor('invitation').createMultiple(store, { email: 'a@b.com,x@y.com' });

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions