add auth api routes

This commit is contained in:
Nathaniel Tampus
2023-03-19 20:53:43 +08:00
parent 1fab992f53
commit 20b26448ae
2 changed files with 85 additions and 6 deletions

View File

@@ -11,9 +11,7 @@ export const fetchSession = async () => {
const user: User = await res.json();
return user;
}
} catch (err) {
console.error(err);
}
} catch (err) {}
};
export const setGuestSession = async (name: string) => {
@@ -34,3 +32,84 @@ export const setGuestSession = async (name: string) => {
console.error(err);
}
};
export const register = async (name: string, password: string, email?: string) => {
try {
const res = await fetch(`${API_URL}/v1/auth/register`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name, password, email })
});
if (res.status === 201) {
const user: User = await res.json();
return user;
} else if (res.status === 409) {
const { message } = await res.json();
return message as string;
}
} catch (err) {
console.error(err);
}
};
export const login = async (name: string, password: string) => {
try {
const res = await fetch(`${API_URL}/v1/auth/login`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name, password })
});
if (res.status === 200) {
const user: User = await res.json();
return user;
} else if (res.status === 404 || res.status === 401) {
const { message } = await res.json();
return message as string;
}
} catch (err) {
console.error(err);
}
};
export const logout = async () => {
try {
const res = await fetch(`${API_URL}/v1/auth/logout`, {
method: "POST",
credentials: "include"
});
if (res.status === 204) {
return true;
}
} catch (err) {
console.error(err);
}
};
export const updateUser = async (email?: string, password?: string) => {
try {
if (!email && !password) return;
const res = await fetch(`${API_URL}/v1/auth/`, {
method: "PATCH",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ email, password })
});
if (res.status === 200) {
const user: User = await res.json();
return user;
} else if (res.status === 409) {
const { message } = await res.json();
return message as string;
}
} catch (err) {
console.error(err);
}
};

View File

@@ -3,14 +3,14 @@ import * as controller from "../controllers/auth.controller.js";
const router = Router();
router.route("/").get(controller.getCurrentSession);
router.route("/").get(controller.getCurrentSession).patch(controller.updateUser);
// create or update guest sessions
router.route("/guest").post(controller.guestSession);
router.route("/logout").post(controller.logoutSession);
//router.route("/register").post(controller.registerUser);
//router.route("/login").post(controller.loginUser);
router.route("/register").post(controller.registerUser);
router.route("/login").post(controller.loginUser);
export default router;