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.)

+3
json javascript rest bookshelf.js


source to share


No one has answered this question yet

See similar questions:

0
How to access data in a `through` table with a bookshelf

or similar:

7494
How can I remove a specific element from an array in JavaScript?
5722
How can I remove a property from a JavaScript object?
5129
How do I return a response from an asynchronous call?
2687
Can CSS be applied to half a character?
2480
How do I send JSON data using Curl from terminal / command line to Test Spring REST?
1690
How does data binding work in AngularJS?
1567
Converting form data to JavaScript object with jQuery
1349
Why can't Python parse this JSON data?
811
How can I reformat JSON in Notepad ++?
0
Bookshelf: How to Apply BelongsToMany?



All Articles
Loading...
X
Show
Funny
Dev
Pics