TLA Line data Source code
1 : use anyhow::Context;
2 : use bytes::Buf;
3 : use hyper::{header, Body, Request, Response, StatusCode};
4 : use serde::{Deserialize, Serialize};
5 :
6 : use super::error::ApiError;
7 :
8 CBC 1931 : pub async fn json_request<T: for<'de> Deserialize<'de>>(
9 1931 : request: &mut Request<Body>,
10 1931 : ) -> Result<T, ApiError> {
11 1931 : json_request_or_empty_body(request)
12 122 : .await?
13 1931 : .context("missing request body")
14 1931 : .map_err(ApiError::BadRequest)
15 1931 : }
16 :
17 : /// Will be removed as part of <https://github.com/neondatabase/neon/issues/4282>
18 1997 : pub async fn json_request_or_empty_body<T: for<'de> Deserialize<'de>>(
19 1997 : request: &mut Request<Body>,
20 1997 : ) -> Result<Option<T>, ApiError> {
21 1997 : let body = hyper::body::aggregate(request.body_mut())
22 123 : .await
23 1997 : .context("Failed to read request body")
24 1997 : .map_err(ApiError::BadRequest)?;
25 1997 : if body.remaining() == 0 {
26 8 : return Ok(None);
27 1989 : }
28 1989 : serde_json::from_reader(body.reader())
29 1989 : .context("Failed to parse json request")
30 1989 : .map(Some)
31 1989 : .map_err(ApiError::BadRequest)
32 1997 : }
33 :
34 7644 : pub fn json_response<T: Serialize>(
35 7644 : status: StatusCode,
36 7644 : data: T,
37 7644 : ) -> Result<Response<Body>, ApiError> {
38 7644 : let json = serde_json::to_string(&data)
39 7644 : .context("Failed to serialize JSON response")
40 7644 : .map_err(ApiError::InternalServerError)?;
41 7644 : let response = Response::builder()
42 7644 : .status(status)
43 7644 : .header(header::CONTENT_TYPE, "application/json")
44 7644 : .body(Body::from(json))
45 7644 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
46 7644 : Ok(response)
47 7644 : }
|