KeystoneJS: How to set a field to receive randomly generated value?

旧时模样 提交于 2019-12-11 06:50:10

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/52688378/keystonejs-how-to-set-a-field-to-receive-randomly-generated-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!