xssbook/public/js/api.js
2023-01-22 22:04:26 -05:00

57 lines
1.5 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 json = await response.json()
return { status: response.status, msg: json.msg, json }
}
const login = async (email, password) => {
return await request('/auth/login', {email, password})
}
const register = async (first, last, email, password, gender, month, day, year) => {
return await request('/auth/register', {first, last, email, password, gender, month, day, year})
}
const loadposts = async (page) => {
return await request('/posts/load', {page})
}
const loadusersposts = async (id) => {
return await request('/posts/user', {id})
}
const loadusers = async (ids) => {
return await request('/users/load', {ids})
}
const loadallusers = async () => {
return await request('/users/all', {})
}
const loadself = async () => {
return await request("/auth/self", {})
}
const postcomment = async (id, content) => {
return await request('/posts/comment', {id, content}, 'PUT')
}
const postlike = async (id, state) => {
return await request('/posts/like', {id, state}, 'PUT')
}
const createpost = async (content) => {
return await request('/posts/create', {content})
}