Skip to content

Commit 115a850

Browse files
committed
Added wrap and _unwrap methods to Model.js to mimmic Laravel's resource data wrapping. This is a shortcut for , , , that allows you to not only automatically unwrap using the standard first, find, get, all methods but also change what the wrapper key is in case you don't want to use the standard 'data' property
1 parent 88fbe9a commit 115a850

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

src/Model.js

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,29 @@ export default class Model extends StaticModel {
5656
return 'id'
5757
}
5858

59+
/**
60+
* The "data" wrapper that should be applied.
61+
*
62+
* @return {string|null}
63+
*/
64+
wrap() {
65+
return ''
66+
}
67+
68+
/**
69+
* Unwrap the response using the property defined in the wrap() method
70+
*
71+
* @return {object|array} The unwraped response
72+
*/
73+
_unwrap(response) {
74+
const wrapper = this.wrap()
75+
if (wrapper) {
76+
return response[wrapper] || response
77+
} else {
78+
return response
79+
}
80+
}
81+
5982
getPrimaryKey() {
6083
return this[this.primaryKey()]
6184
}
@@ -365,7 +388,7 @@ export default class Model extends StaticModel {
365388
item = response[0]
366389
}
367390

368-
return item || {}
391+
return this._unwrap(item || {})
369392
})
370393
}
371394

@@ -386,7 +409,7 @@ export default class Model extends StaticModel {
386409
method: 'GET'
387410
})
388411
).then((response) => {
389-
return this._applyInstance(response.data)
412+
return this._applyInstance(this._unwrap(response.data))
390413
})
391414
}
392415

@@ -421,7 +444,7 @@ export default class Model extends StaticModel {
421444
response.data = collection
422445
}
423446

424-
return response.data
447+
return this._unwrap(response.data)
425448
})
426449
}
427450

0 commit comments

Comments
 (0)