进入FuanaDB官网进行注册:
类似于数据库的Table,FaunaDB使用集合概念,索引可方便对数据集合进行查找等操作。
FaunaDB提供原生查询语言,简称FQL(Fauna Query Language),用法可见FQL使用。
如查找People集合中,名字为特定值的记录:
CreateIndex({
name: "people_search_by_first",
source: Collection("People"),
terms: [
{
field: ["data", "first"]
}
]
})
Map(
Paginate(
Match(Index("people_search_by_first"), "Alan")
),
Lambda(
"person",
Get(Var("person"))
)
)
注册与登录都需要先判断用户是否存在,首先创建索引:
CreateIndex({
name: "search_by_name",
source: Collection("userdata"),
terms: [
{
field: ["data", "name"]
}
]
})
判断是否存在用户:
If(Equals(Select("data", Count(Paginate(
Match(Index("search_by_name"), "testname")
))), [1]), "Existing", "Not Existing")
注册时,通过以下方式创建用户:
Create(
Collection("userdata"),
{
data: {
"name": "testname",
"pwd": "123456",
"email": "test@gmail.com"
},
}
)
在FaunaDB控制台添加Function, 命名为“register_user”:
Query(
Lambda(
["username", "password", "email"],
If(
Equals(
Select(
"data",
Count(Paginate(Match(Index("search_by_name"), Var("username"))))
),
[1]
),
404,
Create(Collection("userdata"), {
data: {
name: Var("username"),
pwd: Var("password"),
email: Var("email")
}
})
)
)
)
使用以下命令在FaunaDB的Shell命令行中测试:
Call("register_user", ["testname", "123456", "test@gmail.com"])
后续我们在管理界面创建一个Role,保证该Role可以访问以上函数。
直接判断存在账户及密码,命名为函数“login_user”:
Query(
Lambda(
["username", "password"],
Count(
Filter(
Select("data", Paginate(Match(Index("search_by_name"), Var("username")))),
Lambda("record", Equals(Select("pwd", Select("data", Get(Var("record")))), Var("password")))
)
)
)
)
使用以下命令在FaunaDB的Shell命令行中测试:
Call("login_user", ["testname", "123456"])
为客户端创建Role,仅允许访问所添加的函数:
为客户端Role创建密钥,供客户端访问以上函数:
复制(6)中生成的密钥,访问登录与注册函数即可, 以C#为例:
static async Task DoQuery(FaunaClient client)
{
Value result = await client.Query(Call(Function("login_user"), "testname", "1234656"));
}
public void Login()
{
var client = new FaunaClient(endpoint: ENDPOINT, secret: SECRET);
DoQuery(client).Wait();
}
Map(
Select("data", Paginate(Match(Index("search_by_name"), "testname"))),
Lambda("record", Select("pwd", Select("data", Get(Var("record")))))
)
Filter(
Select("data", Paginate(Match(Index("search_by_name"), "testname"))),
Lambda("record", Equals(Select("pwd", Select("data", Get(Var("record")))), "123456")
)
)