DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: d3a667702c2b38c541448eb2418db62e24bd29b8 deck-builder/api/src/handlers/user/create.rs -rw-r--r-- 1.5 KiB
d3a66770Jonni Liljamo feat(client): move connect screen stuff to own module 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),
        },
    }
}