问题
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);
}
回答1:
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);
}
The problem is that the user didn't know their own ID so that is missing in newData
.
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);
}
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.
来源:https://stackoverflow.com/questions/61526061/aqueduct-how-to-save-client-data-without-the-user-id-in-my-backend