api for fetching user profile

This commit is contained in:
Nathaniel Tampus
2023-04-05 22:29:54 +08:00
parent bec764dcee
commit bdc8dab1ad
4 changed files with 61 additions and 0 deletions

18
client/src/lib/user.ts Normal file
View File

@@ -0,0 +1,18 @@
import { API_URL } from "@/config";
import type { User, Game } from "@chessu/types";
export const getProfileData = async (name: string) => {
try {
// TODO: handle caching more efficiently?
const res = await fetch(`${API_URL}/v1/users/${name}`, {
next: { revalidate: 10 }
});
if (res && res.status === 200) {
const data: User & { recentGames: Game[] } = await res.json();
return data;
}
} catch (err) {
console.error(err);
}
};

View File

@@ -0,0 +1,33 @@
import type { Request, Response } from "express";
import xss from "xss";
import GameModel from "../db/models/game.model.js";
import UserModel from "../db/models/user.model.js";
export const getUserProfile = async (req: Request, res: Response) => {
try {
const name = xss(req.params.name);
const users = await UserModel.findByNameEmail({ name, email: name });
if (!users || !users.length) {
res.status(404).end();
return;
}
const recentGames = await GameModel.findByUserId(users[0].id as number);
const publicUser = {
id: users[0].id,
name: users[0].name,
wins: users[0].wins,
losses: users[0].losses,
draws: users[0].draws
};
res.status(200).json({ ...publicUser, recentGames });
} catch (err: unknown) {
console.log(err);
res.status(500).end();
}
};

View File

@@ -1,10 +1,12 @@
import { Router } from "express";
import games from "./games.route.js";
import auth from "./auth.route.js";
import users from "./users.route.js";
const router = Router();
router.use("/games", games);
router.use("/auth", auth);
router.use("/users", users);
export default router;

View File

@@ -0,0 +1,8 @@
import { Router } from "express";
import * as controller from "../controllers/users.controller.js";
const router = Router();
router.route("/:name").get(controller.getUserProfile);
export default router;