xssbook/public/js/api.js
2023-01-28 02:51:34 -05:00

67 lines
1.9 KiB
JavaScript

const endpoint = '/api'
const request = async (url, body, method) => {
if (method === undefined) method = 'POST'
const response = await fetch(endpoint + url, {
method,
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
}
});
if (response.status == 401) {
location.href = 'login'
}
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
const json = await response.json()
return { status: response.status, msg: json.msg, json }
} else {
const msg = await response.text();
return { status: response.status, msg }
}
}
const login = async (email, password) => {
return await request('/auth/login', {email, password})
}
const register = async (firstname, lastname, email, password, gender, day, month, year) => {
return await request('/auth/register', {firstname, lastname, email, password, gender, day, month, year})
}
const logout = async () => {
return await request('/auth/logout', {})
}
const loadpostspage = async (page) => {
return await request('/posts/page', {page})
}
const loadusersposts = async (user_id) => {
return await request('/posts/user', {user_id})
}
const loadusers = async (ids) => {
return await request('/users/load', {ids})
}
const loaduserspage = async (page) => {
return await request('/users/page', {page})
}
const loadself = async () => {
return await request("/users/self", {})
}
const postcomment = async (post_id, content) => {
return await request('/posts/comment', {post_id, content}, 'PATCH')
}
const postlike = async (post_id, state) => {
return await request('/posts/like', {post_id, state}, 'PATCH')
}
const createpost = async (content) => {
return await request('/posts/create', {content})
}