问题描述
当我不知道用户ID时如何为用户保存数据?我想将其保存在我的渡槽后端中,以便保护和查询当前用户数据?
How can I save data for a user when I don't know their user ID? I want to save it in my Aqueduct back end so I can protect and query current user data?
@Operation.post()
Future<Response> addData(@Bind.body(ignore: ['id']) Data newData) async {
final query = Query<Data>(context)..values = newData;
final insertData = await query.insert();
return Response.ok(insertData);
}
推荐答案
渡槽自动生成用户ID创建新用户时。该ID与用户的登录凭据或访问令牌相关联。
Aqueduct automatically generates a user ID when you create a new user. That id is associated with the user's login credentials or access token.
在您的示例中,用户以数据模型传递了一些数据:
In your example here the user passed in some data in a Data model:
@Operation.post()
Future<Response> addData(@Bind.body(ignore: ['id']) Data newData) async {
final query = Query<Data>(context)..values = newData;
final insertData = await query.insert();
return Response.ok(insertData);
}
问题是用户不知道自己的ID,因此在 newData
中丢失。
The problem is that the user didn't know their own ID so that is missing in newData
.
假设您有路线,则您可以这样获得用户ID:
Assuming that you have the route protected with an Authorizer, then you can get the user ID like this:
final userID = request.authorization.ownerID;
因此您可以像这样使用它:
So you can use it like this:
@Operation.post()
Future<Response> addData(@Bind.body(ignore: ['id']) Data newData) async {
final userID = request.authorization.ownerID;
final query = Query<Data>(context)
..values.id = userId
..values.something = newData.something
..values.another = newData.another;
final insertData = await query.insert();
// if insert was successful then...
return Response.ok(insertData);
}
顺便说一句,由于您将插入的数据返回给用户,将包含userId。但是,
By the way, since you are returning the inserted data to the user, it will include the userId with it. The client shouldn't need that, though.
这篇关于渡槽-如何在没有后端用户ID的情况下保存客户端数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!