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