我正在后端使用 NodeJS/ExpressJS(作为 REST api)并在前端使用 React 构建一个 Web 应用程序。
这更像是一个一般性问题,而不是一个具体问题:在描述模型的属性时,不重复自己的最佳实践是什么?我将它们单独放在后端的三个冗余位置:
打字稿界面
interface ICat extends Document {
name: string;
age: number;
}
猫鼬模式
type CatModel = mongoose.Model<ICat>;
const catSchema = new mongoose.Schema<ICat, CatModel>({
name: {
type: String,
trim: true,
required: true,
},
age: {
type: Number,
required: true,
},
});
const Cat = mongoose.model<ICat, CatModel>("Cat", catSchema);
Joi 验证
const validateCat = (catData: { [key: string]: any }) => {
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().required(),
});
return schema.validate(catData);
};
如果我想让前端了解模型的属性并确保在发送到服务器之前进行正确的验证,我还需要在那里提供 Typescript 接口和 Joi 验证。
按照我的理解,上面的例子并不干燥。是的,我想在数据到达数据库附近之前验证来自客户端的数据。
那么,保持代码简洁的最佳实践是什么?
非常感谢!
我也有类似的需求。我一直在使用 mongoose-tsgen 并且效果很好。