never expiring pastes

This commit is contained in:
Dominic Harris 2022-02-28 16:51:37 -05:00
parent c53caba8b6
commit 7f06a905d6
No known key found for this signature in database
GPG Key ID: 93CCF85F3E2A4F65
4 changed files with 23 additions and 6 deletions

View File

@ -2,13 +2,13 @@ CREATE TABLE IF NOT EXISTS pastes (
"id" TEXT PRIMARY KEY,
"content" TEXT NOT NULL,
"views" BIGINT DEFAULT 0,
"expires_at" TIMESTAMP WITHOUT TIME ZONE NOT NULL,
"expires_at" TIMESTAMP WITHOUT TIME ZONE,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT(NOW() AT TIME ZONE 'utc')
);
CREATE OR REPLACE FUNCTION deleteExpiredPastes() RETURNS trigger AS $pastes_expire$
BEGIN
DELETE FROM pastes WHERE "expires_at" < now() AT TIME ZONE 'utc';
DELETE FROM pastes WHERE "expires_at" IS NOT NULL AND "expires_at" < now() AT TIME ZONE 'utc';
RETURN NEW;
END;
$pastes_expire$ LANGUAGE plpgsql;

View File

@ -11,7 +11,7 @@ use actix_web::{
};
use config::Config;
use chrono::Duration;
use chrono::{Duration, NaiveDateTime};
use models::{ApiError, ApiResponse, GetPasteResponse, NewPasteResponse, PartialPaste, Paste};
use nanoid::nanoid;
use sqlx::{postgres::PgPoolOptions, types::chrono::Utc, PgPool};
@ -88,7 +88,14 @@ async fn new_paste(state: web::Data<AppState>, data: web::Json<PartialPaste>) ->
}
let id = nanoid!(10);
let expires_at = Utc::now() + Duration::days(state.config.pastes.days_til_expiration);
let expires_at;
if state.config.pastes.days_til_expiration == -1 {
expires_at = None;
} else {
expires_at = Some(Utc::now() + Duration::days(state.config.pastes.days_til_expiration));
}
let res =
sqlx::query(r#"INSERT INTO pastes("id", "content", "expires_at") VALUES ($1, $2, $3)"#)
@ -109,6 +116,7 @@ async fn new_paste(state: web::Data<AppState>, data: web::Json<PartialPaste>) ->
});
}
Err(e) => {
println!("{}", e);
return HttpResponse::InternalServerError().json(ApiResponse {
success: false,
data: ApiError {

View File

@ -7,7 +7,7 @@ pub struct Paste {
pub id: String,
pub content: String,
pub views: i64,
pub expires_at: NaiveDateTime,
pub expires_at: Option<NaiveDateTime>,
}
#[derive(Deserialize)]
@ -32,7 +32,7 @@ pub struct GetPasteResponse {
pub id: String,
pub content: String,
pub views: i64,
pub expires_at: NaiveDateTime,
pub expires_at: Option<NaiveDateTime>,
}
#[derive(Serialize)]

9
config.example.json Normal file
View File

@ -0,0 +1,9 @@
{
"pastes": {
"character_limit": 40000,
"days_til_expiration": 7
},
"databases": {
"postgres_uri": "postgres://postgres:postgres@localhost:5432/zer0bin"
}
}