public async Task <IActionResult> CreateAsync([FromBody] CreateCommentRequest comment) { var getQuery = new CreateComment.Command(comment); var res = await _mediator.Send(getQuery); return(Ok(true)); }
public async Task <bool> Handle(CreateCommentRequest message, IOutputPort <CreateCommentResponse> outputPort) { var requestId = message.RequestId; var parentId = message.ParentId; var author = message.Author; var content = message.Content; var response = await _commentRepository.CreateCommentOfRequest( requestId, content, author, parentId ); if (!response.Success) { outputPort.Handle( new CreateCommentResponse(response.Errors) ); return(false); } outputPort.Handle(new CreateCommentResponse(response.Id, response.CreatedAt)); return(true); }
public async Task <IActionResult> Create([FromBody] CreateCommentRequest commentRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var existedPost = await _postsRepository.GetPostByIdAsync(commentRequest.PostId.Value); if (existedPost == null) { return(BadRequest(new { error = $"Post with Id {commentRequest.PostId} does not exist" })); } var comment = _mapper.Map <Comment>(commentRequest); comment.UserId = HttpContext.GetUserId(); var created = await _commentsRepository.CreateCommentAsync(comment); if (created) { var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; var locationUri = baseUrl + "/" + ApiRoutes.Comments.Get.Replace("{commentId}", comment.Id.ToString()); return(Created(locationUri, _mapper.Map <CommentResponse>(comment))); } return(NotFound()); }
public async Task <IActionResult> CommentCreate([FromBody] CreateCommentRequest request) { var keyAuthResult = await _authService.AuthByApiKey(); if (keyAuthResult.User == null) { return(BadRequest(ErrorResponse.GetErrorList(keyAuthResult.ErrorText))); } var ticket = _ticketService.GetTicket(request.TicketId); if (ticket == null) { return(BadRequest(ErrorResponse.GetErrorList($"Ticket: {request.TicketId} does not exist!"))); } var newComment = _ticketService.AddComment(ticket.Id, request.Comment, keyAuthResult.User.Identity.Name); if (newComment == null) { return(BadRequest(ErrorResponse.GetErrorList("Validation Error"))); } var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; var locationUrl = baseUrl + "/" + ApiRoutes.Comments.Get.Replace("{id}", newComment.Id.ToString()); var response = _mapper.Map <CommentResponse>(newComment); return(Created(locationUrl, response)); }
public async Task <IActionResult> CreateReply([FromBody] CreateCommentRequest commentRequest, [FromRoute] Guid commentId) { var comment = await _commentService.GetCommentByIdAsync(commentId); if (comment == null) { return(NotFound()); } var reply = new Comment { CommentText = commentRequest.CommentText, ParentId = commentId, PostId = comment.PostId, UserId = HttpContext.GetUserId() }; await _commentService.CreateCommentAsync(reply); var locationUrl = _uriService.GetCommentById(comment.Id.ToString()); reply.User = await _userManager.FindByIdAsync(comment.UserId); return(Created(locationUrl, new Response <CommentResponse>(_mapper.Map <CommentResponse>(reply)))); }
public async Task <PostVM> CreateComment(CreateCommentRequest request, ApplicationUser applicationUser) { var post = await _context.Posts.Where(x => x.PostID == request.PostID).FirstOrDefaultAsync(); if (post == null) { return(null); } // Khởi tạo và add commnet vào bảng commnet var commnet = new Comment() { Content = request.Content, DateCreated = DateTime.Now, Author = applicationUser.FullName, Parent = 0, Id = applicationUser.Id, PostID = request.PostID }; _context.Comments.Add(commnet); await _context.SaveChangesAsync(); // Xử lý post view model hiển thị về cho user var postVM = _public_post_service.PublicDeatilPost(request.PostID); return(await postVM); }
public async Task <CreateCommentResponse> CreatePostComment(Guid postId, [FromBody] CreateCommentRequest model) { var comment = new Models.PostComment { Comment = model.Comment, OwnerId = CurrentUserId, OwnerName = User.Identity.Name, PostId = postId }; await _postCommentRepo.AddAsync(comment); var response = new CreateCommentResponse { Id = comment.Id, Comment = comment.Comment, PostId = comment.PostId, OwnerName = comment.OwnerName, CreatedDate = comment.Created }; await _postMessageHubContext.Clients.All.InvokeAsync("AddCommentSuccess", response); return(response); }
public async Task<UserItem> GetUser() { CreateCommentRequest res = new CreateCommentRequest(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url + "me"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); UserItem user = new UserItem(); var uri = new Uri(url + "me"); try { HttpResponseMessage response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<Response<UserItem>>(content).Data; } } catch (Exception ex) { Debug.WriteLine(@" ERROR {0}", ex.Message); } return await Task.FromResult(user); }
private async void PublishExecute() { if (string.IsNullOrWhiteSpace(Text)) { CurtainPrompt.ShowError("Looks like you forgot to include some text."); return; } var newCommentRequest = new CreateCommentRequest(_postId, Text); IsLoading = true; var restResponse = await _findierService.SendAsync <CreateCommentRequest, string>(newCommentRequest); IsLoading = false; if (restResponse.IsSuccessStatusCode) { CurtainPrompt.Show("Comment published!"); NavigationService.GoBack(); } else { CurtainPrompt.ShowError(restResponse.DeserializedResponse?.Error ?? "Problem publishing comment."); } }
public async Task <Comment> AddCommentAsync(string userId, string articleId, CreateCommentRequest createComment) { createComment.UserId = userId; var comment = await this.articleService.AddCommentAsync(articleId, createComment); return(comment); }
public async Task <ActionResult <CommentResponse> > Create(CreateCommentRequest comment) { comment.Created = DateTime.Now; comment.OwnerId = Account.Id; await _commentService.CreateComment(comment); return(Ok(comment)); }
/// <summary> /// Creates a comment that is posted to the given conversation via the conversation id /// </summary> /// <param name="conversationId">Id of the requested conversation</param> /// <param name="comment">The comment to be created consisting of the body and author id</param> /// <returns>The newly created comment details including the UNIX timestamp denoting the time posted</returns> public Comment Create(string conversationId, CreateCommentRequest comment) { var request = base.BuildRequest(Method.POST); request.AddParameter("conversationId", conversationId, ParameterType.UrlSegment); return(_client.Execute <Comment>(request, comment)); }
public async Task <IActionResult> CreateComment(CreateCommentRequest request) { var response = await mediator.Send(request); logger.LogResponse($"User #{HttpContext.GetCurrentUserId()} created comment #{response.Comment?.Id} in post #{request.PostId}", response.Error); return(response.IsSucceeded ? (IActionResult)Ok(response) : BadRequest(response)); }
public static Comment FromCreateRequest(CreateCommentRequest request) { return(new Comment { Body = request.Body, ThreadId = request.ThreadId, }); }
public async Task <ActionResult <CommentResponse> > CreateComment ( [FromServices] ICommentsService commentsService, [FromBody] CreateCommentRequest request ) { request.UserId = IdentityHelper.GetIdFromUser(User); return(await commentsService.CreateComment(request)); }
public static Comment ToCommentModel(this CreateCommentRequest request) { return(new Comment { Body = request.Body, ProductRating = request.ProductRating, ProductId = request.ProductId, }); }
public async Task <ActionResult <int> > AddComment(CreateCommentRequest request) { var commentModel = request.ToCommentModel(); commentModel.DateOfAdding = DateTime.UtcNow; var createdCommentId = await _commentService.Create(commentModel, request.ParentId); return(Ok(createdCommentId)); }
public async Task <ActionResult> createComment([FromBody] CreateCommentRequest comment) { var status = await _mediator.Send(comment); if (status == 1) { return(Ok(ResultObject.Ok <NullDataType>(null, "Thêm thành công."))); } return(Ok(ResultObject.Fail("Thất bại."))); }
//[Authorize(Roles = "manager, user, publisher, moderator, admin")] public async Task <IActionResult> LeaveComment(int productId, CreateCommentRequest request) { var commentModel = request.ToCommentModel(); commentModel.ProductId = productId; commentModel.DateOfAdding = DateTime.UtcNow; await _commentService.Create(commentModel, request.ParentId); return(Ok()); }
public void ApiV1ItemByAgencyByIdByVersionCommentPostAsyncWithHttpInfo() { configuration = GetClientConfig(); CommentApi commentApiTest = new CommentApi(configuration); CreateCommentRequest createcommentRequest = new CreateCommentRequest { Comment = "test of commments" }; ApiResponse <object> response = commentApiTest.ApiV1ItemByAgencyByIdByVersionCommentPostWithHttpInfo(agencyTest, new Guid("52c5dd34-1b5f-460b-8904-6f0f2897f6a1"), 1L, createcommentRequest); Assert.Equal(200, response.StatusCode); }
public async Task <IActionResult> CreateArticleComment(string id, [FromBody] CreateCommentRequest updateRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var comment = await _service.CreateArticleComment(id, updateRequest); var location = string.Format("/api/articles/{0}", id); return(Created(location, comment)); }
public async Task <IActionResult> Create([FromBody] CreateCommentRequest request) { var post = await this.postService.GetAsync(request.PostId); if (post == null) { return(new BadRequestResult()); } var comment = this.commentService.CreateAsync(request.PostId, "user", request.Content); return(new JsonResult(comment)); }
// Ajout d'un commentaire public async Task <bool> SubmitComment(string comment, int place) { try { httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://td-api.julienmialon.com/places/" + place + "/comments"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Barrel.Current.Get <LoginResult>(key: "Login").AccessToken); CreateCommentRequest commentR = new CreateCommentRequest(comment); string data = JsonConvert.SerializeObject(commentR); request.Content = new StringContent(data, Encoding.UTF8, "application/json"); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { if (await GetUser()) { return(true); } } else { if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool token = await RefreshToken(); if (token) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Barrel.Current.Get <LoginResult>(key: "Login").AccessToken); response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { if (await GetUser()) { return(true); } } } } } return(false); } catch (Exception e) { return(false); } }
// ======================================== // constructor // ======================================== public CreateCommentEdgeTool( IModelFactory modelFactory, IEdge feedback, Predicate <object> sourceConnectionJudge, Predicate <object> targetConnectionJudge, Action <IEdge> edgeInitializer ) : base(feedback) { _request = new CreateCommentRequest(); _request.ModelFactory = modelFactory; _sourceConnectionJudge = sourceConnectionJudge; _targetConnectionJudge = targetConnectionJudge; _edgeInitializer = edgeInitializer; }
public async Task <IActionResult> Create(CreateCommentRequest request, int article_id) { var userId = User.Claims.GetUserId(); if (userId == null) { return(BadRequest()); } if (await _commentService.Create(article_id, userId.Value, request.Text)) { return(Ok()); } return(BadRequest()); }
public async Task WithInactiveUser_ShouldFail() { // Arrange var content = "some content"; var req = new CreateCommentRequest(userInactiveAuth.Id, threadVisisble.Id, content); var createCommentUseCase = ServiceProvider.GetService <CreateCommentUseCase>(); // Act var result = await createCommentUseCase.Handle(req); // Assert Assert.Single(result.ValidationErrors); Assert.Contains(CreateCommentError.UserIsInactive, result.ValidationErrors); }
public async Task WithEmptyContent_ShouldFail() { // Arrange var content = ""; var req = new CreateCommentRequest(userActiveAuth.Id, threadVisisble.Id, content); var createCommentUseCase = ServiceProvider.GetService <CreateCommentUseCase>(); // Act var res = await createCommentUseCase.Handle(req); // Assert Assert.Single(res.ValidationErrors); Assert.Contains(CreateCommentError.ContentIsEmpty, res.ValidationErrors); }
public async Task WithInexistentThread_ShouldFail() { // Arrange var threadId = Guid.NewGuid(); var content = "some content"; var req = new CreateCommentRequest(userActiveAuth.Id, threadId, content); var createCommentUseCase = ServiceProvider.GetService <CreateCommentUseCase>(); // Act var result = await createCommentUseCase.Handle(req); // Assert Assert.Single(result.ValidationErrors); Assert.Contains(CreateCommentError.ThreadDoesNotExist, result.ValidationErrors); }
public async Task WithInexistentAuth_ShouldFail() { // Arrange var authId = Guid.NewGuid(); var content = "some content"; var req = new CreateCommentRequest(authId, threadVisisble.Id, content); var createCommentUseCase = ServiceProvider.GetService <CreateCommentUseCase>(); // Act var result = await createCommentUseCase.Handle(req); // Assert Assert.Single(result.ValidationErrors); Assert.Contains(CreateCommentError.AuthenticationIsInvalid, result.ValidationErrors); }
public async Task <IActionResult> Create([FromBody] CreateCommentRequest commentRequest, [FromRoute] Guid postId) { var comment = new Comment { CommentText = commentRequest.CommentText, PostId = postId, UserId = HttpContext.GetUserId() }; await _commentService.CreateCommentAsync(comment); var locationUrl = _uriService.GetCommentById(comment.Id.ToString()); comment.User = await _userManager.FindByIdAsync(comment.UserId); return(Created(locationUrl, new Response <CommentResponse>(_mapper.Map <CommentResponse>(comment)))); }