42 lines
1.3 KiB
Rust
42 lines
1.3 KiB
Rust
use axum::{Extension, extract::Path, http::StatusCode};
|
|
use sqlx::SqlitePool;
|
|
|
|
use crate::{auth::User, paste::PasteType};
|
|
|
|
use super::{db_error, input::PasteInput};
|
|
|
|
pub async fn create(
|
|
db: &SqlitePool,
|
|
id: Option<Path<String>>,
|
|
user: Option<Extension<User>>,
|
|
input: PasteInput,
|
|
paste_type: PasteType,
|
|
) -> Result<String, StatusCode> {
|
|
let mut id = id.map(|Path(id)| id).filter(|id| {
|
|
!matches!(id.as_str(), "list" | "once" | "to" | "static") && !id.contains('/')
|
|
});
|
|
let owner = user.map(|Extension(user)| user.username);
|
|
let expiration = input.expiration()?;
|
|
loop {
|
|
let created = sqlx::query_scalar(
|
|
"INSERT INTO notes (id, type, content, language, expiration, max_views, created_at, owner)
|
|
VALUES (COALESCE(?, lower(hex(randomblob(12)))), ?, ?, ?, ?, ?, unixepoch(), ?)
|
|
ON CONFLICT(id) DO NOTHING RETURNING id",
|
|
)
|
|
.bind(id.as_deref())
|
|
.bind(&paste_type)
|
|
.bind(&input.content)
|
|
.bind(&input.language)
|
|
.bind(expiration)
|
|
.bind(input.max_views)
|
|
.bind(owner.as_deref())
|
|
.fetch_optional(db)
|
|
.await
|
|
.map_err(db_error)?;
|
|
if let Some(id) = created {
|
|
return Ok(id);
|
|
}
|
|
id = None;
|
|
}
|
|
}
|