forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

format.rs34 lines, 1.2 KiBHistoryRawDownload
1//! POST /format: formats a code block for the editor. The formatters run on a blocking
2//! thread, and the answer is the formatted code as plain text.
3
4use serde::Deserialize;
5use topcoat::{
6 Result,
7 router::{StatusCode, content::Json, error::content_too_large, route},
8};
9
10/// The most `code` the endpoint accepts, in bytes.
11const MAX_CODE_BYTES: usize = 256 * 1024;
12
13#[derive(Deserialize)]
14struct FormatInput {
15 /// Canonical lowercase language id, such as `rust`.
16 language: String,
17 /// The code to format.
18 code: String,
19}
20
21/// POST /format: the formatted code, or 422 with the reason it could not be formatted.
22#[route(POST "/format")]
23pub async fn format_code(Json(input): Json<FormatInput>) -> Result<(StatusCode, String)> {
24 if input.code.len() > MAX_CODE_BYTES {
25 return Err(content_too_large().into());
26 }
27 let result = tokio::task::spawn_blocking(move || crate::format::format(&input.language, &input.code))
28 .await
29 .map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
30 Ok(match result {
31 Ok(text) => (StatusCode::OK, text),
32 Err(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
33 })
34}