Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

How to make one Ember data model fits for multiple forms?

I have to handle something HTTP methods from external api (create and update) by DS.store. Server expects other fields for create method, than for update method. For example:

Expected params for POST in json:

{
  "name": "string",
  "email": "string",
  "login": "string",
  "password": "string",
} 

Expected params for PUT method:

{
  "name": "string",
  "subdomain": "string",
  "person": "string",
}

Obviously, i have other forms for these actions, but DS.store takes all fields from DS.model for request. My model:

export default DS.Model.extend({
  login: DS.attr('string'),
  password: DS.attr('string'),
  name: DS.attr('string'),
  subdomain: DS.attr('string'),
  email: DS.attr('string'),
  person: DS.attr('string'),
});

So, for example, POST request looks like this:

{
  "name": "somethingName",
  "email": "[email protected]",
  "login": "login",
  "password": "passw",
  "subdomain": null,
  "person": null
} 

Even, if not expected keys have null or undefined value, my server returns 400 ( unrecognized parameters "subdomian", "person"). Unfortunately, I don't have access to the server, so I have to pass to the server only expected params. I tried also something like this in serializer:

attrs: {
        person: { serialize: false },
        subdomain: { serialize: false },
}

But naturally it was creating errors for PUT request... Is there something way to pass only params included in my html form, or delete params, which have null/undefined value before request to the server? I know, I can use something other than DS.store, but I want to have clear code with only one middleman between client and server.

Upvotes: 1

Views: 41

Answers (1)

XYZ
XYZ

Reputation: 27387

In Ember Data, the Adapter determines how data is persisted to a backend data store, such as the URL format and headers for a REST API.

If you have one model that has exceptional rules for communicating with its backend than the others you can create a Model specific Adapter by running the command

ember generate adapter adapter-name

For more information about customizing your adapter read the link below,

https://guides.emberjs.com/v2.6.0/models/customizing-adapters/

Upvotes: 1

Related Questions