summary refs log tree commit diff
path: root/src/api/routes/users/@me/pomelo.ts
blob: 11e0517d3bf219e6ffb5bb7c431afa8e4770fc9f (plain) (blame)
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
import { route } from "@spacebar/api";
import { Config, FieldErrors, User } from "@spacebar/util";
import { Request, Response, Router } from "express";
import { HTTPError } from "lambert-server";
import { UniqueUsernameAttemptSchema } from "@spacebar/schemas";
const router = Router();

// https://discord-userdoccers.vercel.app/resources/user#create-pomelo-migration
router.post(
    "/",
    route({
        description: "Claims a unique username for the user. Returns the updated user object on success. Fires a User Update Gateway event.",
        requestBody: "UniqueUsernameAttemptSchema",
        responses: {
            200: { body: "PrivateUserResponse" },
            400: { body: "APIErrorResponse" },
        },
    }),
    async (req: Request, res: Response) => {
        const body = req.body as UniqueUsernameAttemptSchema;
        const { uniqueUsernames } = Config.get().general;
        if (!uniqueUsernames) {
            throw new HTTPError("Unique Usernames feature is not enabled on this instance.", 400);
        }

        const isAvailable = await User.isUsernameAvailable(body.username);

        if (!isAvailable) {
            throw FieldErrors({
                username: {
                    code: "USERNAME_TOO_MANY_USERS",
                    message: req?.t("auth:register.USERNAME_TOO_MANY_USERS") || "",
                },
            });
        }

        const user = await User.findOneOrFail({
            where: {
                id: req.user_id,
            },
        });

        user.legacy_username = user.username;
        user.username = body.username;
        user.discriminator = "0";
        const newUser = await user.save();

        res.json(newUser.toPrivateUser());
    },
);

export default router;