Zzhongliangjun1发布于 13 年前
031050
http request 参数传到server JSON.parse后,属性的value均是string的,每次都是自己手动转成对应的类型,如Number、Date等。
schemajs 提供了通过自己定义输入参数的schema(指定属性类型),从而帮你生成所需的最终对象,属性类型都会根据schema帮你转好。这很类似于mongoose。
但是,其实我只想在schema中申明需要转型的属性,多余的别管太多,向下面这样要是写完完整的schema真的好辛苦。
var reviewDemo =
{
"reviewId" : "133",
"reviewBody" : "烤羊棒子很好次,一人一根也就足够了,一边点评一边点的菜,酸奶,鱼鱼都是不错的 感觉很快能吃饱 三个人两百多没吃到几样菜。",
"price" : { "priceTitle" : "价格", "priceValue" : "34", "unit" : "元" },
"scores" : [
{ "scoreTitle" : "环境", "scoreValue" : "3", "scoreDescribe" : "好" },
{ "scoreTitle" : "服务", "scoreValue" : "3", "scoreDescribe" : "好" },
{ "scoreTitle" : "口味", "scoreValue" : "4", "scoreDescribe" : "很好" }
],
"tags" : [ { "tagTitle" : "餐厅氛围", "tagValueList" : [ "商务宴请", "朋友聚会" ] } ]
}
var reviewModel = schemajs.create(
{
reviewId : { type:'int', filters:['trim', 'toInt'], required:true, error:'review must has a reviewId' },
price : {
type:'object',
schema:{
priceValue : { type:'float', filters:['trim', 'toFloat'], properties:{min:0}, error:'priceValue is not a valid priceValue' }
}
}
}
);
var form = reviewModel.validate(reviewDemo);
console.log(util.inspect(form.data));
但人家schemajs说了:‘strict mode, dissallowing extra parameters from being passed in’。 上面这样写schema,没定义的属性全没了,泪奔~
大家是怎么解决的?