amiel / ember-data-url-templates

an ember-addon to allow building urls with url templates instead of defining buildURL
https://github.com/amiel/ember-data-url-templates/wiki
MIT License
129 stars 22 forks source link

What do I do if my create and update api is different? #39

Closed dineshvgp closed 6 years ago

dineshvgp commented 6 years ago

This is how my api looks:

Find all - /api/contacts/{contact_id}/notes create - /api/contacts/{contact_id}/notes update - /api/contacts/{contact_id}/notes/{note_id}

// adapter:
{
  urlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  createRecordUrlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  urlSegments: {
    contactId: (type, id, snapshot) => snapshot.adapterOptions.contactId,
    noteId: (type, id, snapshot) => snapshot.adapterOptions.noteId
  }
}
amiel commented 6 years ago

Hi @dineshvgp,

It looks like you've already figured out how to customize the template specifically for create. Defining a separate template for update is similar:

{
  urlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  createRecordUrlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  updateRecordUrlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes/{noteId}',
  urlSegments: {
    contactId: (type, id, snapshot) => snapshot.adapterOptions.contactId,
    noteId: (type, id, snapshot) => snapshot.adapterOptions.noteId
  }
}

Also, note that if this is the note adapter, then you can get the id by using {id}, like this:

{
  urlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  createRecordUrlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  updateRecordUrlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes/{id}',
  urlSegments: {
    contactId: (type, id, snapshot) => snapshot.adapterOptions.contactId,
  }
}

And, if this is the case, you can use the {/id} syntax to only add that segment if there is an id present. Given your urls, it looks like it could work to use the same template for all three requests, like this:

{
  urlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes{/id}',
  urlSegments: {
    contactId: (type, id, snapshot) => snapshot.adapterOptions.contactId,
  }
}

I hope this helps. Would you close the issue if you feel this is resolved?

dineshvgp commented 6 years ago

Thanks a lot for your detailed answer @amiel. I'll try out and close it, once that works.