From 4480080496a15c88e6962eca277486d2eedfb4bf Mon Sep 17 00:00:00 2001 From: Alexandertp Date: Wed, 11 Sep 2024 15:34:03 +0200 Subject: [PATCH] Implement backend for displaying user info Frontend display currently not working Co-authored-by: Reimar --- .../Users/Queries/QueryUsersByIds.cs | 32 +++++++++++++++++++ API/Controllers/UsersController.cs | 17 ++++++---- .../Repositories/IUserRepository.cs | 1 + .../Repositories/UserRepository.cs | 13 ++++++++ API/Program.cs | 2 +- Mobile/lib/api.dart | 6 ++-- Mobile/lib/reviewlist.dart | 23 +++++++++++++ Mobile/pubspec.lock | 8 ++--- Mobile/pubspec.yaml | 2 +- 9 files changed, 89 insertions(+), 15 deletions(-) create mode 100644 API/Application/Users/Queries/QueryUsersByIds.cs diff --git a/API/Application/Users/Queries/QueryUsersByIds.cs b/API/Application/Users/Queries/QueryUsersByIds.cs new file mode 100644 index 0000000..034f56d --- /dev/null +++ b/API/Application/Users/Queries/QueryUsersByIds.cs @@ -0,0 +1,32 @@ +using API.Models; +using API.Persistence.Repositories; +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.Web.CodeGenerators.Mvc.Templates.BlazorIdentity.Pages.Manage; +using Newtonsoft.Json.Linq; + +namespace API.Application.Users.Queries +{ + public class QueryUsersByIds + { + private readonly IUserRepository _repository; + + public QueryUsersByIds(IUserRepository repository) + { + _repository = repository; + } + + public async Task>> Handle(List ids) + { + List users = await _repository.QueryUsersByIdsAsync(ids); + + if (users == null) + { + return new ConflictObjectResult(new { message = "No user on given Id" }); + } + + return new OkObjectResult(users.Select(user => new { id = user.Id, email = user.Email, username = user.Username, profilePicture = user.ProfilePicture, createdAt = user.CreatedAt })); + + } + + } +} diff --git a/API/Controllers/UsersController.cs b/API/Controllers/UsersController.cs index 985d255..f9959e7 100644 --- a/API/Controllers/UsersController.cs +++ b/API/Controllers/UsersController.cs @@ -22,36 +22,35 @@ namespace API.Controllers { private readonly QueryAllUsers _queryAllUsers; private readonly QueryUserById _queryUserById; + private readonly QueryUsersByIds _queryUsersByIds; private readonly CreateUser _createUser; private readonly UpdateUser _updateUser; private readonly DeleteUser _deleteUser; private readonly LoginUser _loginUser; private readonly TokenHelper _tokenHelper; - - private readonly IUserRepository _repository; public UsersController( QueryAllUsers queryAllUsers, QueryUserById queryUserById, + QueryUsersByIds queryUsersByIds, CreateUser createUser, UpdateUser updateUser, DeleteUser deleteUser, LoginUser loginUser, TokenHelper tokenHelper, IUserRepository repository - ) + ) { _queryAllUsers = queryAllUsers; _queryUserById = queryUserById; + _queryUsersByIds = queryUsersByIds; _createUser = createUser; _updateUser = updateUser; _deleteUser = deleteUser; _loginUser = loginUser; _tokenHelper = tokenHelper; _repository = repository; - - } [HttpPost("login")] @@ -73,9 +72,15 @@ namespace API.Controllers return await _queryUserById.Handle(id); } + [HttpGet("UsersByIds")] + public async Task>> GetUsersByIds(List userIds) + { + return await _queryUsersByIds.Handle(userIds); + } + [Authorize] [HttpPut] - public async Task PutUser([FromForm ]UpdateUserDTO UpdateUserDTO) + public async Task PutUser([FromForm] UpdateUserDTO UpdateUserDTO) { return await _updateUser.Handle(UpdateUserDTO); } diff --git a/API/Persistence/Repositories/IUserRepository.cs b/API/Persistence/Repositories/IUserRepository.cs index 9f2584d..737fb2d 100644 --- a/API/Persistence/Repositories/IUserRepository.cs +++ b/API/Persistence/Repositories/IUserRepository.cs @@ -8,6 +8,7 @@ namespace API.Persistence.Repositories Task DeleteUserAsync(string id); Task> QueryAllUsersAsync(); Task QueryUserByIdAsync(string id); + Task> QueryUsersByIdsAsync(List ids); Task QueryUserByEmailAsync(string email); Task UpdateUserAsync(User user); Task QueryUserByRefreshTokenAsync(string refreshToken); diff --git a/API/Persistence/Repositories/UserRepository.cs b/API/Persistence/Repositories/UserRepository.cs index e007973..12a04c0 100644 --- a/API/Persistence/Repositories/UserRepository.cs +++ b/API/Persistence/Repositories/UserRepository.cs @@ -1,5 +1,6 @@ using API.Models; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Internal; using Microsoft.VisualStudio.Web.CodeGenerators.Mvc.Templates.BlazorIdentity.Pages; namespace API.Persistence.Repositories @@ -25,6 +26,18 @@ namespace API.Persistence.Repositories } } + public async Task> QueryUsersByIdsAsync(List ids) + { + try + { + return _context.Users.Where(user => ids.Contains(user.Id)).ToList(); + } + catch (Exception) + { + return []; + } + } + public async Task CreateUserAsync(User user) { try diff --git a/API/Program.cs b/API/Program.cs index 522abfe..a5cd0be 100644 --- a/API/Program.cs +++ b/API/Program.cs @@ -43,7 +43,7 @@ namespace API builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); - + builder.Services.AddScoped(); IConfiguration Configuration = builder.Configuration; diff --git a/Mobile/lib/api.dart b/Mobile/lib/api.dart index e99a012..fa8b837 100644 --- a/Mobile/lib/api.dart +++ b/Mobile/lib/api.dart @@ -22,7 +22,7 @@ Future request(BuildContext? context, ApiService service, String method }; final token = prefs.getString('token'); - final Map headers = {}; + final Map headers = {'Accept': 'application/json'}; if (token != null) headers.addAll({'Authorization': 'Bearer $token'}); final http.Response response; @@ -47,7 +47,7 @@ Future request(BuildContext? context, ApiService service, String method ); } } catch (e) { - debugPrint(e.toString()); + debugPrint('Can\'t send requst: ' + e.toString()); messenger?.showSnackBar(const SnackBar(content: Text('Unable to connect to server'))); return null; } @@ -58,7 +58,7 @@ Future request(BuildContext? context, ApiService service, String method messenger?.showSnackBar(SnackBar(content: Text(json['message'] ?? json['title']))); debugPrint('API error: ' + json['message']); } catch (e) { - debugPrint(e.toString()); + debugPrint('Can\'t parse response: ' + e.toString()); messenger?.showSnackBar(SnackBar(content: Text('Something went wrong (HTTP ${response.statusCode})'))); } return null; diff --git a/Mobile/lib/reviewlist.dart b/Mobile/lib/reviewlist.dart index 4dc2d1b..7be225d 100644 --- a/Mobile/lib/reviewlist.dart +++ b/Mobile/lib/reviewlist.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:mobile/base/sidemenu.dart'; @@ -12,6 +14,27 @@ class ReviewListPage extends StatefulWidget { } class _ReviewListState extends State { + List users = []; + + @override + void didChangeDependencies() async { + super.didChangeDependencies(); + + final arg = ModalRoute.of(context)!.settings.arguments as models.ReviewList; + final reviews = arg.reviews; + + final userIds = reviews.map((review) => review.userId).toSet().toList(); + final queryParams = userIds.map((id) => "userIds=$id"); + final queryString = "?${queryParams.join("&")}"; + + final response = await api.request(context, api.ApiService.auth, 'GET', '/api/Users/UsersByIds$queryString', null); + if (response == null) return; + + debugPrint('response: ' + response); + + users = (jsonDecode(response) as List).map((user) => models.User.fromJson(user)).toList(); + } + @override Widget build(BuildContext context) { final arg = ModalRoute.of(context)!.settings.arguments as models.ReviewList; diff --git a/Mobile/pubspec.lock b/Mobile/pubspec.lock index f388662..f835c02 100644 --- a/Mobile/pubspec.lock +++ b/Mobile/pubspec.lock @@ -194,10 +194,10 @@ packages: dependency: "direct dev" description: name: flutter_lints - sha256: "9e8c3858111da373efc5aa341de011d9bd23e2c5c5e0c62bccf32438e192d7b1" + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" url: "https://pub.dev" source: hosted - version: "3.0.2" + version: "4.0.0" flutter_map: dependency: "direct main" description: @@ -412,10 +412,10 @@ packages: dependency: transitive description: name: lints - sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "4.0.0" lists: dependency: transitive description: diff --git a/Mobile/pubspec.yaml b/Mobile/pubspec.yaml index 9b609b5..3f66b54 100644 --- a/Mobile/pubspec.yaml +++ b/Mobile/pubspec.yaml @@ -53,7 +53,7 @@ dev_dependencies: # activated in the `analysis_options.yaml` file located at the root of your # package. See that file for information about deactivating specific lint # rules and activating additional ones. - flutter_lints: ^3.0.0 + flutter_lints: ^4.0.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec