DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: fc94ea592f1e8c226f5154b5a6a4d783bdfdb36c deck-builder/api/src/handlers/user/create.rs -rw-r--r-- 1.5 KiB
fc94ea59Jonni Liljamo chore(api): update dev scripts 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * This file is part of laurelin/api
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use actix_web::{post, web, HttpResponse, Responder};
use email_address::EmailAddress;

use laurelin_shared::error::api::APIError;

use crate::{actions, models, PgPool};

#[post("/api/user")]
pub(crate) async fn create(
    pool: web::Data<PgPool>,
    user: web::Json<models::InsertableUser>,
) -> impl Responder {
    if user.username.len() < 3 {
        return HttpResponse::BadRequest().json(APIError::UserUsernameTooShort);
    }

    if user.password.len() < 8 {
        return HttpResponse::BadRequest().json(APIError::UserPasswordTooShort);
    }

    if !EmailAddress::is_valid(&user.email) {
        return HttpResponse::BadRequest().json(APIError::UserEmailInvalid);
    }

    let user_create = web::block(move || {
        let mut conn = match pool.get() {
            Err(_) => return Err(APIError::DatabasePoolGetFailed),
            Ok(conn) => conn,
        };
        actions::user::create(&mut conn, &user.0)
    })
    .await;

    match user_create {
        Err(_err) => {
            // TODO: handle?
            return HttpResponse::InternalServerError().json(APIError::Undefined);
        }
        Ok(user_res) => match user_res {
            Err(err) => {
                return HttpResponse::InternalServerError().json(err);
            }
            Ok(user) => HttpResponse::Ok().json(user),
        },
    }
}