public HttpResponseMessage SendRequest( [FromBody] ConnectionRequestSendModel model, [FromUri] string sessionKey) { var responseMsg = this.PerformOperationAndHandleExceptions(() => { var sender = this.GetUserBySessionKey(sessionKey); var receiver = this.db.Users.All().FirstOrDefault(u => u.Id == model.ReceiverId); if (receiver == null) { throw new ArgumentException("Invalid receiverId"); } if (sender.Id == receiver.Id) { throw new ArgumentException("You can't send connection request to yourself"); } var existingConnection = sender.Connections.FirstOrDefault(c => c.OtherUserId == receiver.Id); if (existingConnection != null) { throw new ArgumentException("You already have a connection with that user"); } // Check if user A is sending a connection request to user B for a second time var existingConnectionRequest = receiver.ConnectionRequests .FirstOrDefault(cr => cr.SenderId == sender.Id && cr.ReceiverId == receiver.Id); if (existingConnectionRequest != null) { throw new ArgumentException("That user already has a connection request from you"); } // Check if the user A is trying to send a connection request to user B, // but user B has already sent a connection request to user A existingConnectionRequest = sender.ConnectionRequests .FirstOrDefault(cr => cr.SenderId == receiver.Id && cr.ReceiverId == sender.Id); if (existingConnectionRequest != null) { throw new ArgumentException("You have a connection request from that user"); } var connectionRequest = new ConnectionRequest() { Receiver = receiver, Sender = sender }; receiver.ConnectionRequests.Add(connectionRequest); this.db.Users.Update(receiver); this.db.SaveChanges(); var response = this.Request.CreateResponse(HttpStatusCode.Created); return(response); }); return(responseMsg); }
public void Send_WhenSessionKeyIsInvalid_ShouldReturnBadRequest() { using (new TransactionScope()) { this.db.Users.Add(firstUser); this.db.Users.Add(secondUser); this.db.SaveChanges(); var conRequestModel = new ConnectionRequestSendModel() { ReceiverId = this.secondUser.Id }; var response = this.httpServer.CreatePostRequest( string.Format("/api/connectionRequests/send?sessionKey={0}", "Invalid session key"), conRequestModel); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } }
public void Send_WhenDataIsValid_ShouldSendConnectionRequest() { using (new TransactionScope()) { this.db.Users.Add(firstUser); this.db.Users.Add(secondUser); this.db.SaveChanges(); var conRequestModel = new ConnectionRequestSendModel() { ReceiverId = this.secondUser.Id }; var response = this.httpServer.CreatePostRequest( string.Format("/api/connectionRequests/send?sessionKey={0}", this.firstUser.SessionKey), conRequestModel); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); var connectionRequests = this.db.ConnectionRequests .All() .Where(cr => cr.ReceiverId == this.secondUser.Id); Assert.AreEqual(1, connectionRequests.Count()); } }