Beispiel #1
0
        public async Task <ActionResult <Entry> > Post(string userId, Entry entry)
        {
            try
            {
                if (!HttpContext.User.CompareIdWithTokenId(userId))
                {
                    return(Unauthorized());
                }
                var user = await repository.GetUserById(userId, true);

                if (user == null)
                {
                    return(BadRequest("The user is not found."));
                }
                entry.Id = 0; // The Id is generated by the DB.
                user.Entries.Add(entry);
                if (await repository.SaveChangesAsync())
                {
                    var link = linkGenerator.GetPathByAction("Get", "Entries", new { userId, entryId = entry.Id });
                    return(Created(link, entry));
                }
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Database Failure"));
            }
            return(BadRequest());
        }
        public async Task <ActionResult <UserModel> > Put(string id, User user, bool includeEntries = false)
        {
            try
            {
                if (!HttpContext.User.CompareIdWithTokenId(id))
                {
                    return(Unauthorized());
                }
                var userFromId = await repository.GetUserById(id);

                if (userFromId == null)
                {
                    return(BadRequest("User not found."));
                }

                var userFromEmail = await repository.GetUserByEmail(user.Email);

                if (userFromEmail != null && !userFromId.Id.Equals(userFromEmail?.Id))
                {
                    BadRequest("Email already used.");
                }

                mapper.Map(user, userFromId);

                if (await repository.SaveChangesAsync())
                {
                    user = await repository.GetUserById(id, includeEntries);

                    var link = linkGenerator.GetPathByAction("Get", "Users", new { id = user.Id });
                    return(Accepted(link, mapper.Map <User, UserModel>(user)));
                }
                return(StatusCode(StatusCodes.Status304NotModified, mapper.Map <User, UserModel>(user)));
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }