Ejemplo n.º 1
0
        public static async Task <IActionResult> CompleteCreateImage
            ([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "images/{id}")] HttpRequest req,
            TraceWriter log,
            string id)
        {
            // get request body
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            CompleteCreateImageRequest data;

            try
            {
                data = JsonConvert.DeserializeObject <CompleteCreateImageRequest>(requestBody);
            }
            catch (JsonReaderException)
            {
                return(new BadRequestObjectResult(new { error = "Body should be provided in JSON format." }));
            }

            // validate request body
            if (data == null || string.IsNullOrEmpty(data.CategoryId))
            {
                return(new BadRequestObjectResult(new { error = "Missing required property 'categoryId'." }));
            }

            // get the user ID
            if (!await UserAuthenticationService.GetUserIdAsync(req, out var userId, out var responseResult))
            {
                return(responseResult);
            }

            try
            {
                var(result, previewUrl) = await ImagesService.CompleteAddImageNoteAsync(id, userId, data.CategoryId);

                switch (result)
                {
                case CompleteAddImageNoteResult.Success:
                    return(new OkObjectResult(new
                    {
                        previewUrl = previewUrl
                    }));

                case CompleteAddImageNoteResult.ImageTooLarge:
                    return(new BadRequestObjectResult(new { error = "Image is too large. Images must be 4MB or less." }));

                case CompleteAddImageNoteResult.InvalidImage:
                    return(new BadRequestObjectResult(new { error = "Image is not in a valid format. Supported formats are JPEG (image/jpeg) and PNG (image/png)." }));

                case CompleteAddImageNoteResult.ImageNotUploaded:
                    return(new BadRequestObjectResult(new { error = "Image has not yet been uploaded." }));

                case CompleteAddImageNoteResult.ImageAlreadyCreated:
                    return(new BadRequestObjectResult(new { error = "Image has already been created." }));

                default:
                    throw new InvalidOperationException($"Unexpected result '{result}' from {nameof(ImagesService)}.{nameof(ImagesService.CompleteAddImageNoteAsync)}");
                }
            }
            catch (Exception ex)
            {
                log.Error("Unhandled exception", ex);
                return(new ExceptionResult(ex, false));
            }
        }