按理说,接下来应该讲讲 cue 的操作符了,但是直接讲太过单调,于是直接上约束规则吧。
cue 他支持制定数据的规则,所以在接受数据时一些简单的约束交个 cue 就可以了。
1、规则定义
这里我们以提交一篇博客文章为例子:
post: {title: "这里是标题"body: "这里是文章内容"user_id: 1}
假如我们这就只提交这三个参数,现在我们需要对这三个参数进行约束。
这时我们就需要使用到 cue 里面类似继承的特性:
#post: {
title: string
body: string
user_id: int
}
post: #post & {
title: "这里是标题"
body: "这里是文章内容"
user_id: 1
}
我们声明了一个 #post 的变量,因为 # 开头的变量在导出时不会被输出,我们的规则不需要导出。
接下来我们把它放在了 post 变量后面,你可以理解让他继承 #post 这个变量,最后加了一个 & 连接起来。
这个约束就设置好了。
接下来我们测试下:
#post: {
title: string
body: string
user_id: int
}
post: #post & {
title: "这里是标题"
body: "这里是文章内容"
}
$ cue export hello.cue
post.user_id: incomplete value int
#post: {
title: string
body: string
user_id: int
}
post: #post & {
title: "这里是标题"
body: "这里是文章内容"
user_id: "34"
}
$ cue export hello.cue
post.user_id: conflicting values int and "34" (mismatched types int and string):
./hello.cue:5:11
./hello.cue:11:11
2、或
加入我们的标题既支持 string 类型又支持 int 类型,该怎么处理呢?
#post: {
title: string | int
body: string
user_id: int
}
3、允许为空
很多时候,我们某些变量是允许为空的:
#post: {
title: string | int
body?: string
user_id: int
}
在 key 后面加上 ? 就可以了,此时 body 这个参数就允许为空,可以不传值了。
4、默认值
更多时候我们更希望使用默认值,而不是为空:
#post: {
title: string | int
body?: string
user_id: int | *1
}
这样我们的 user_id 默认值就是 1 了,当然其他类型也是支持的,只要 * 后面的值和前面的类型对应上即可。
5、变量引用
我们可以在 cue 里面使用类似枚举的功能:
#post: {
title: string
body: string
user_id: int
type?: string
}
// 定义一个枚举
#postType: {
post: "post"
page: "page"
}
post: #post & {
title: "这里是标题"
body: "这里是文章内容"
user_id: 1
type: #postType.post
}
这里的 type 变量取的就是 #postType 下面的 post 的值:
$ cue export hello.cue
{
"post": {
"title": "这里是标题",
"body": "这里是文章内容",
"user_id": 1,
"type": "post"
}
}
6、模板
刚才那只是变量引用,我们还可以直接把那个模板拿过来:
#admin: {
name: "admin"
}
post: {
title: "这里是标题"
body: "这里是文章内容"
user_info: #admin
}
此时我们导出:
$ cue export hello.cue
{
"post": {
"title": "这里是标题",
"body": "这里是文章内容",
"user_info": {
"name": "admin"
}
}
}
