KeystoneJS: How to set a field to receive randomly

2019-08-13 09:45发布

I'm creating a model that I will use to authenticate users for API access, and I have a secret field where I want to store a Base64 encoded uuid/v4 generated value.

I went through the different field types and options, but still not seeing how I could achieve this.

Is there a way to hook in model instance creation, and set the value of my secret field ?

2条回答
狗以群分
2楼-- · 2019-08-13 10:28

Yes, you can use the pre hooks.

In your situation, the basics would be:

AuthenticationModel.schema.pre("save", function(next) {
  const secretValue = generateSecretValue();
  this.secret = secretValue;
  next();
});

That would go before your final AuthenticationModel.register(); in your model.js file.

查看更多
看我几分像从前
3楼-- · 2019-08-13 10:29

This is how I set it up, also with the pre-save hook. My problem before was that I was getting the same random number again until I restarted the server.

Store.schema.pre('save', function (next) {
    if (!this.updateId && this.isNew) {
        // generates a random ID when the item is created
        this.updateId = Math.random().toString(36).slice(-8);
    }
    next();
});

Using this.isNew was also useful in my case.

查看更多
登录 后发表回答