1

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);
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
delmin
  • 2,330
  • 5
  • 28
  • 54

1 Answers1

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • Thank you very much for the answer.. It was really helpful and I really appreciate that.. I had problem from the beginning understand where the `request` statement is coming from therefore I did't think about getting the user id that way... Just for clarification can you explain where is the `request` statement coming from? – delmin May 01 '20 at 06:50
  • 1
    @delmin Your controller extends `ResourceController` and `request` is a member variable of that class. – Suragch May 01 '20 at 06:57