chyabrung-cli 0.2.5

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
use chyabrung::prelude::*;
use chyabrung::storage::Storage;

const ALLOWED: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "avif", "pdf", "txt", "csv"];

pub struct UploadController;

#[controller]
impl UploadController {
    async fn store(_user: Auth, storage: Storage, mut form: Multipart) -> Result<Json<serde_json::Value>> {
        while let Some(field) = form.next_field().await? {
            if let Some(name) = field.file_name().map(str::to_owned) {
                let ext = std::path::Path::new(&name)
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(str::to_ascii_lowercase)
                    .filter(|e| ALLOWED.contains(&e.as_str()))
                    .ok_or_else(|| Error::unprocessable(format!("Only these file types are allowed: {}", ALLOWED.join(", "))))?;
                let key = format!("uploads/{}.{ext}", chyabrung::auth::random_token(12));
                storage.put(&key, field.bytes().await?).await?;
                return Ok(Json(json!({ "path": key, "url": storage.url(&key) })));
            }
        }
        Err(Error::bad_request("Send a file in a multipart field"))
    }
}