This pull request is to handle request to JSON API’s with and without data wrapping.
Basically you only need to configure your model and define how your data is wrapper in each response operation.
Configration
You only need to define de value of dataWrappers()
By default, all models operate without data wrapping, for backward compatibility.
dataWrappers() {
return {
index: null,
store: null,
show: null,
update: null,
destroy: null,
}
}
So, if your API returns all your data inside a data
attribute, then you should set up dataWrappers()
like this:
dataWrappers() {
return {
index: 'data',
store: 'data',
show: 'data',
update: 'data',
destroy: 'data',
}
}
In case your API only wraps the resources collections, then, you only need to set up that response type:
dataWrappers() {
return {
index: 'data',
store: null,
show: null,
update: null,
destroy: null,
}
}
Well, you get the idea...
Model Instance hydration
Another thing this pull request solves is the model hydratation. All models will be hydratated after each CRUD operation. This is usefull if your API returns a full representation of the resource. This avoids a second request to get the new values.
// resource before request
// {
// id: 1,
// username: 'arya'
// email: '[email protected]'
// token: '1234'
// }
// PUT /users/1
let user = new User({ id: 1, email: '[email protected]' })
await user.save()
// response from API for PUT /users/1
// {
// data: {
// id: 1,
// username: 'arya'
// email: '[email protected]'
// token: '1234'
// }
// }
user = {
id: 1,
username: 'arya'
email: '[email protected]'
token: '1234'
}
This is very useful even for a DELETE
request, if you return the deleted values.
Access to response instance on save.
Finally, now, method save()
returns the response instance unmodified. The models are stored in the instance itself (hydrated), but the returned value is the http response. Again, this is useful if we want to access metadata information in the response data.
let user = new User({name: 'Arya'})
res = user.save()
// "user" is the User Instance
user = {
id: 1,
name: 'arya',
}
// "res" is the http response
res = {
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}
Tests...
I've added test for all the cases (I think). By the way, I added some "deprecated" comments (in tests) for methods $get()
, $first()
, $find()
as I think those methods are redundant now? I don't know, what do you think?