Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toJSON() not working for level 3 inclusions #1401

Closed
erikverheij opened this issue May 20, 2015 · 7 comments
Closed

toJSON() not working for level 3 inclusions #1401

erikverheij opened this issue May 20, 2015 · 7 comments
Assignees
Labels

Comments

@erikverheij
Copy link

I'm using the toJSON() method so I can apply lodash methods like _.omit() on the data. In can only get it working until the second inclusion level.

var filter  = { include: {games: 'results'}};
app.models.Challenger.find(filter, function(err, challengers) {
  var challengers = challengers.toJSON();
  console.log(challengers[0].games[0].results[0]);
  // --> Properties of result are only available via the __data property
});

When challengers is returned as HTTP response body the data is returned as expected. Is loopback using a different method than .toJSON() to serialize the data returned to the client?

@raymondfeng
Copy link
Member

Serialization calls .toJSON() recursively as part of JSON.stringify(). There seems to be an issue that in the toJSON() implementation which doesn't go into the 3rd level. We'll investigate.

@raymondfeng
Copy link
Member

It seems to be a user error:

var filter  = { include: {games: 'results'}};
app.models.Challenger.find(filter, function(err, challengers) {
  // Please note challengers is an array, Array.toJSON() doesn't recursively convert all child objects
  var challengers = challengers.toJSON();
  console.log(challengers[0].games[0].results[0]);
  // --> Properties of result are only available via the __data property
});

@erikverheij
Copy link
Author

Ah, that was a typo :( I'll make a test spec to reproduce the issue.

@erikverheij
Copy link
Author

This mocha test reproduces the issue;

var q = require('q');
var loopback = require('loopback');
var app = require('../server');
var assert = require('assert');
var async = require('async');
var _ = require('lodash');


function createSchema() {

  app.dataSource('db', {
    connector: 'memory'
  });

  var ChallengerModel = loopback.createModel(
    {
      name: 'Challenger',
      base: 'PersistedModel',
      properties: {
        name: {
          type: 'string',
        }
      },
      relations: {
        gameParticipations: {
          type: 'hasMany',
          model: 'GameParticipation',
          foreignKey: ''
        }
      }
    }
  );
  var GameParticipationModel = loopback.createModel(
    {
      name: 'GameParticipation',
      base: 'PersistedModel',
      properties: {
        date: {
          type: 'date',
        }
      },
      relations: {
        challenger: {
          type: 'belongsTo',
          model: 'Challenger',
          foreignKey: ''
        },
        results: {
          type: 'hasMany',
          model: 'Result',
          foreignKey: ''
        }
      }
    }
  );
  var ResultModel = loopback.createModel({
    name: 'Result',
    base: 'PersistedModel',
    properties: {
      points: {
        type: 'number',
      }
    },
    relations: {
      gameParticipation: {
        type: 'belongsTo',
        model: 'GameParticipation',
        foreignKey: ''
      }
    }
  });

  app.model(ChallengerModel, { dataSource: 'db' });
  app.model(GameParticipationModel, { dataSource: 'db' });
  app.model(ResultModel, { dataSource: 'db' });

}

function createChallengers(callback){
  app.models.Challenger.create([{name: 'challenger1'}, {name: 'challenger2'}], callback);
}

function createGameParticipations(challengers, callback){
  app.models.GameParticipation.create([
    { challengerId: challengers[0].id, date: Date.now() },
    { challengerId: challengers[0].id, date: Date.now() }
  ], callback);
}

function createResults(gameParticipations, callback){
  app.models.Result.create([
    { gameParticipationId: gameParticipations[0].id, points: 10 },
    { gameParticipationId: gameParticipations[0].id, points: 20 }
  ], callback);
}


before(function importSampleData(done) {

  createSchema();

  async.waterfall([
    createChallengers,
    createGameParticipations,
    createResults,
    function(){ done(); }
  ]);

});


describe('ModelBaseClass.toJSON()', function() {
  it('should recursively serialize objects', function(done) {
    var filter  = { include: { gameParticipations: 'results'} };
    app.models.Challenger.find(filter, function(err, challengers) {

      var levelOneInclusion = challengers[0].toJSON().gameParticipations[0];
      assert(_.isUndefined(levelOneInclusion.__data), '.__data of a level 1 inclusion is undefined.');

      var levelTwoInclusion = challengers[0].toJSON().gameParticipations[0].results[0];
      assert(_.isUndefined(levelTwoInclusion.__data), '__data of a level 2 inclusion is undefined.');
      done();
    });
  });
});

@ritch
Copy link
Member

ritch commented May 21, 2015

@erikverheij thanks for the test case :)

raymondfeng pushed a commit to loopbackio/loopback-datasource-juggler that referenced this issue May 22, 2015
raymondfeng added a commit to loopbackio/loopback-datasource-juggler that referenced this issue May 22, 2015
raymondfeng pushed a commit to loopbackio/loopback-datasource-juggler that referenced this issue May 27, 2015
 * Enhance the apis and add more tests (Raymond Feng)

 * Fix for strongloop/loopback#1401 (Raymond Feng)

 * Fix ReferenceError: definition is not defined (Dmitry Manannikov)

 * Mix in observer apis to the connector (Raymond Feng)

 * Enhance fieldsToArray to consider strict mode (Raymond Feng)
@superkhau
Copy link
Contributor

@raymondfeng Can I close this?

@bajtos
Copy link
Member

bajtos commented Jun 2, 2016

The issue should have been fixed by loopbackio/loopback-datasource-juggler#600. Please open a new issue if the problem still persists.

@bajtos bajtos closed this as completed Jun 2, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants