BookshelfJS: Is it possible to reformat data from `withPivot`
I am using Bookhelf to create a fairly simple RESTful API and would like to return a consistent camelCase format when using underscore_database_columns.
I am using format
and parse
from the documentation to do this successfully, except for the data withPivot
.
All code is simplified from my project, so please ask for any syntax errors etc., they may not exist in my real code
I have two models: Recipe
and Ingredient
.
var Recipe = BaseModel.extend({
tableName: 'recipe',
defaults: { name: null },
ingredients: function () {
return this
.belongsToMany('Ingredient')
.withPivot(['measurement', 'sort_order']);
}
}));
var Ingredient = BaseModel.extend({
tableName: 'ingredients',
defaults: { name: null },
recipes: function () {
return this
.belongsToMany('Recipe');
}
}));
I am asking for the following:
Model
.forge({
id: 1
})
.fetch({
withRelated: ['ingredients']
})
.then(function (model) {
return res.json(model.toJSON());
})
.catch(function (err) {
return done(err);
});
Which returns:
{
"id": 1,
"name": "Yummy Thing",
"ingredients": [
{
"id": 1,
"name": "Food Stuff",
"_pivot_ingredient_id": 1,
"_pivot_recipe_id": 1,
"_pivot_measurement": "Loads",
"_pivot_sort_order": 1
}
]
}
As you can see, the data _pivot
is snake_case as is .withPivot(['measurement', 'sort_order'])
as it points to the table column names, not the attributes.
Is there a way to easily reference and return camelCase pivot data?
I've overridden toJSON
, which works great, but doesn't feel right, given that base models use camelCase by default.
toJSON: function () {
var data = BaseModel.prototype.toJSON.apply(this, arguments);
data.ingredients && (data.ingredients = data.ingredients.map(this.parse));
return data;
}
I am open to using models through
, but I have not been able to work how to return table data through
using a selection. (I am not set to the above JSON format as long as all data is in some form or another.)
source to share
No one has answered this question yet
See similar questions:
or similar: