Jack burridge
Jack burridge

Reputation: 520

User infomation in Loopback

I'm making a games backend in loopback. I have a user model defined as such.

{
  "name": "player",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "stats": {
      "type": "hasOne",
      "model": "stats",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": {}
}

And I have the user stats defined as such:

{
  "name": "stats",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "experience": {
      "type": "number",
      "required": true,
      "default": 0
    },
    "coins": {
      "type": "number",
      "required": true,
      "default": 0
    },
    "titles": {
      "type": [
        "string"
      ],
      "required": true,
      "default": []
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

I want to eventually use the ALCs to so the user then cannot modify their own stats. But at the moment I cant work out how to automatically create the states when a user is registered. My first attempt was to generate the stats by using operation hooks so my player.js file is:

module.exports = function (Player) {
    var app = require('../../server/server');
    Player.observe('after save', function filterProperties(ctx, next) {
        var Stats = app.models.Stats;
        if(ctx.isNewInstance) {
            Stats.create({"playerId": ctx.instance.id});
        }
        next();
    });
};

But in my database nothing is showing up, does anyone know how I can fix this?

Upvotes: 0

Views: 45

Answers (1)

notbrain
notbrain

Reputation: 3396

The first thing I would do is add a proper callback to the Stats.create() method to see why the create method isn't doing what you expect, along with some more logic to send next() depending on the result of the operations. I also changed how you get a reference to the Stats model by accessing it through the Player model.

module.exports = function (Player) {

  Player.observe('after save', function filterProperties(ctx, next) {

    var Stats = Player.app.models.Stats;

    if(ctx.isNewInstance) {

      Stats.create({"playerId": ctx.instance.id}, function(err, stats) {

        if(err) {
          console.log("[Player after save] error creating stats instance for playerId " + ctx.instance.id, err);
          next(err);
        } else {
          console.log("[Player after save] Created new empty stats instance for playerId " + ctx.instance.id, stats);
          next();
        }

      });

    } else {
      console.log("[Player after save] Existing player instance, did not create stats");
      next();

    }

  });

};

Upvotes: 1

Related Questions