Aqueduct - How to save client data without the user ID in my backend

霸气de小男生 提交于 2020-05-16 22:00:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!