//! POST /format: formats a code block for the editor. The formatters run on a blocking //! thread, and the answer is the formatted code as plain text. use serde::Deserialize; use topcoat::{ Result, router::{StatusCode, content::Json, error::content_too_large, route}, }; /// The most `code` the endpoint accepts, in bytes. const MAX_CODE_BYTES: usize = 256 * 1024; #[derive(Deserialize)] struct FormatInput { /// Canonical lowercase language id, such as `rust`. language: String, /// The code to format. code: String, } /// POST /format: the formatted code, or 422 with the reason it could not be formatted. #[route(POST "/format")] pub async fn format_code(Json(input): Json) -> Result<(StatusCode, String)> { if input.code.len() > MAX_CODE_BYTES { return Err(content_too_large().into()); } let result = tokio::task::spawn_blocking(move || crate::format::format(&input.language, &input.code)) .await .map_err(|err| topcoat::Error::from_anyhow(err.into()))?; Ok(match result { Ok(text) => (StatusCode::OK, text), Err(message) => (StatusCode::UNPROCESSABLE_ENTITY, message), }) }