コード例 #1
0
        public async Task <IActionResult> CreatePost([FromForm] string caption,
                                                     [FromForm] IList <IFormFile> uploads,
                                                     [FromRoute] string username)
        {
            if (uploads.Count <= 0)
            {
                return(BadRequest(new { Err = "Cannot create a post without any photo!" }));
            }

            // validate user
            var user = await DbContext.Users.SingleOrDefaultAsync(u => u.Username == username);

            if (user is null)
            {
                return(BadRequest(new { Err = "Unauthorized user!" }));
            }

            var transaction = DbContext.Database.BeginTransaction();

            // create post content
            var post = new Post()
            {
                Caption = caption,
                UserId  = user.Id,
                Created = DateTimeOffset.UtcNow
            };

            DbContext.Add(post);
            await DbContext.SaveChangesAsync();

            post = await DbContext.Posts
                   .Include(p => p.User).ThenInclude(u => u.AvatarPhoto)
                   .Where(p => p.Id == post.Id)
                   .FirstOrDefaultAsync();

            // create file uploads
            var uploadedFiles = uploads.Select(async upload => await PhotoUtils.UploadPhotoAsync(upload, PhotoServingPath))
                                .Select(task => task.Result)
                                .Select(fileName => new Photo()
            {
                PostId   = post.Id,
                FileName = fileName
            });

            DbContext.AddRange(uploadedFiles);
            await DbContext.SaveChangesAsync();

            await transaction.CommitAsync();

            return(Created(Url.Action("GetPostById", "Post", new { id = post.Id }), ResponseModelFactory.Create(post)));
        }