KeystoneJS:如何设置一个字段来接收随机生成的值?
KeystoneJS: How to set a field to receive randomly generated value?
我正在创建一个模型,我将使用它来验证用户的 API 访问权限,并且我有一个 secret
字段,我想在其中存储一个 Base64
编码的 uuid/v4
生成的值。
我查看了不同的字段类型和选项,但仍然不知道如何实现。
有没有办法挂钩模型实例创建,并设置我的 secret
字段的值?
是的,您可以使用 pre hooks。
在你的情况下,基本情况是:
AuthenticationModel.schema.pre("save", function(next) {
const secretValue = generateSecretValue();
this.secret = secretValue;
next();
});
那会在你的 model.js 文件中的最终 AuthenticationModel.register();
之前。
我就是这样设置的,还有预保存挂钩。我之前的问题是,在我重新启动服务器之前,我再次获得相同的随机数。
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();
});
使用 this.isNew
对我来说也很有用。
我正在创建一个模型,我将使用它来验证用户的 API 访问权限,并且我有一个 secret
字段,我想在其中存储一个 Base64
编码的 uuid/v4
生成的值。
我查看了不同的字段类型和选项,但仍然不知道如何实现。
有没有办法挂钩模型实例创建,并设置我的 secret
字段的值?
是的,您可以使用 pre hooks。
在你的情况下,基本情况是:
AuthenticationModel.schema.pre("save", function(next) {
const secretValue = generateSecretValue();
this.secret = secretValue;
next();
});
那会在你的 model.js 文件中的最终 AuthenticationModel.register();
之前。
我就是这样设置的,还有预保存挂钩。我之前的问题是,在我重新启动服务器之前,我再次获得相同的随机数。
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();
});
使用 this.isNew
对我来说也很有用。