forked from Anvilcraft/jmserver
Add random endpoint
This commit is contained in:
parent
c4ce0ad4f1
commit
efc419e5df
2 changed files with 42 additions and 0 deletions
|
@ -102,6 +102,30 @@ async fn users(db_pool: web::Data<MySqlPool>) -> impl Responder {
|
|||
}
|
||||
}
|
||||
|
||||
#[get("/v1/random")]
|
||||
async fn random(params: web::Query<MemeFilterQuery>, db_pool: web::Data<MySqlPool>) -> impl Responder {
|
||||
let q = Meme::get_random(params.0, db_pool.get_ref()).await;
|
||||
match q {
|
||||
Ok(random) => HttpResponse::Ok().json(MemeResponse {
|
||||
status: 200,
|
||||
error: None,
|
||||
meme: Some(random)
|
||||
}),
|
||||
Err(err) => match err {
|
||||
Error::RowNotFound => HttpResponse::NotFound().json(MemeResponse {
|
||||
status: 404,
|
||||
error: Some(String::from("Meme not found")),
|
||||
meme: None
|
||||
}),
|
||||
_ => HttpResponse::InternalServerError().json(MemeResponse {
|
||||
status: 500,
|
||||
error: Some(String::from("Internal Server Error")),
|
||||
meme: None
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: Implement random meme endpoint
|
||||
//TODO: Implement upload endpoint
|
||||
|
||||
|
@ -112,4 +136,5 @@ pub fn init(cfg: &mut web::ServiceConfig) {
|
|||
cfg.service(categories);
|
||||
cfg.service(user);
|
||||
cfg.service(users);
|
||||
cfg.service(random);
|
||||
}
|
||||
|
|
|
@ -45,6 +45,23 @@ impl Meme {
|
|||
Ok(q)
|
||||
}
|
||||
|
||||
pub async fn get_random(params: MemeFilterQuery, pool: &MySqlPool) -> Result<Meme> {
|
||||
let q: Meme = sqlx::query("SELECT memes.id, user, filename, category, name, UNIX_TIMESTAMP(timestamp) AS ts FROM memes, users WHERE memes.user = users.id AND (category LIKE ? AND name LIKE ? AND filename LIKE ?) ORDER BY RAND()")
|
||||
.bind(params.category.unwrap_or(String::from("%")))
|
||||
.bind(format!("%{}%", params.user.unwrap_or(String::from(""))))
|
||||
.bind(format!("%{}%", params.search.unwrap_or(String::from(""))))
|
||||
.map(|row: MySqlRow| Meme::from(DBMeme {
|
||||
id: row.get("id"),
|
||||
filename: row.get("filename"),
|
||||
user: row.get("name"),
|
||||
userdir: row.get("user"),
|
||||
category: row.get("category"),
|
||||
timestamp: row.get("ts"),
|
||||
}))
|
||||
.fetch_one(pool).await?;
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl From<DBMeme> for Meme {
|
||||
|
|
Loading…
Reference in a new issue