Skip to content

Commit

Permalink
feat(code): refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
dewanakl committed Dec 19, 2024
1 parent 674089c commit 0c0bfad
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 39 deletions.
4 changes: 2 additions & 2 deletions js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ export const admin = (() => {
comment.init();

try {
// window.atob can throw error
if (!session.isAdmin() || !session.getToken() || (JSON.parse(window.atob(session.getToken().split('.')[1]))?.exp ?? 0) < (Date.now() / 1000)) {
const jwt = session.decode();
if (!jwt || (jwt.exp ?? 0) < (Date.now() / 1000)) {
throw new Error('invalid token');
}

Expand Down
11 changes: 8 additions & 3 deletions js/guest.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,18 +145,23 @@ export const guest = (() => {
return;
}

comment.init();
progress.add();
progress.add();
comment.init();

session.guest()
.then((res) => {
if (res.code !== 200) {
progress.invalid('request');
return res;
}

return comment.comment()
progress.complete('request');
comment.comment()
.then(() => progress.complete('comment'))
.catch(() => progress.invalid('comment'));
});
})
.catch(() => progress.invalid('request'));
};

return {
Expand Down
21 changes: 17 additions & 4 deletions js/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ export const HTTP_DELETE = 'DELETE';
export const request = (method, path) => {

const controller = new AbortController();
const header = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});

offline.addAbort(() => controller.abort());

let url = document.body.getAttribute('data-url');
let req = {
method: String(method).toUpperCase(),
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
}),
headers: header,
signal: controller.signal,
};

Expand Down Expand Up @@ -60,6 +62,9 @@ export const request = (method, path) => {
throw new Error(err);
});
},
/**
* @returns {Promise<boolean>}
*/
download() {
return fetch(url + path, req)
.then((res) => {
Expand Down Expand Up @@ -101,6 +106,10 @@ export const request = (method, path) => {
throw new Error(err);
});
},
/**
* @param {string} token
* @returns {this}
*/
token(token) {
if (session.isAdmin()) {
req.headers.append('Authorization', 'Bearer ' + token);
Expand All @@ -110,6 +119,10 @@ export const request = (method, path) => {
req.headers.append('x-access-key', token);
return this;
},
/**
* @param {object} body
* @returns {this}
*/
body(body) {
req.body = JSON.stringify(body);
return this;
Expand Down
83 changes: 62 additions & 21 deletions js/session.js
Original file line number Diff line number Diff line change
@@ -1,67 +1,108 @@
import { dto } from './dto.js';
import { storage } from './storage.js';
import { progress } from './progress.js';
import { request, HTTP_POST, HTTP_GET } from './request.js';

export const session = (() => {

let session = null;
/**
* @type {ReturnType<typeof storage>}
*/
let ses = null;

const getToken = () => session.get('token');
/**
* @returns {string}
*/
const getToken = () => ses.get('token');

/**
* @param {object} body
* @returns {Promise<boolean>}
*/
const login = (body) => {
return request(HTTP_POST, '/api/session')
.body(body)
.send(dto.tokenResponse)
.then((res) => {
if (res.code === 200) {
session.set('token', res.data.token);
}
.then(
(res) => {
if (res.code === 200) {
setToken(res.data.token);
}

return res;
})
.then((res) => res.code === 200, () => false);
return res.code === 200;
},
() => false
);
};

const logout = () => session.unset('token');
/**
* @returns {void}
*/
const logout = () => ses.unset('token');

const isAdmin = () => String(getToken() ?? '.').split('.').length === 3;
/**
* @param {string} token
* @returns {void}
*/
const setToken = (token) => ses.set('token', token);

/**
* @returns {boolean}
*/
const isAdmin = () => getToken().split('.').length === 3;

/**
* @returns {Promise<ReturnType<typeof dto.baseResponse<object>>}
*/
const guest = () => {
progress.add();
const config = storage('config');

return request(HTTP_GET, '/api/config')
.token(document.body.getAttribute('data-key'))
.send()
.then((res) => {
if (res.code !== 200) {
progress.invalid('request');
return res;
}

const config = storage('config');
for (let [key, value] of Object.entries(res.data)) {
config.set(key, value);
}

session.set('token', document.body.getAttribute('data-key'));
progress.complete('request');

setToken(document.body.getAttribute('data-key'));
return res;
}).catch(() => {
progress.invalid('request');
});
};

/**
* @returns {object|null}
*/
const decode = () => {
if (!isAdmin()) {
return null;
}

try {
return JSON.parse(window.atob(getToken().split('.')[1]));
} catch {
return null;
}
};

/**
* @returns {void}
*/
const init = () => {
session = storage('session');
ses = storage('session');
};

return {
init,
guest,
login,
logout,
decode,
isAdmin,
setToken,
getToken,
};
})();
38 changes: 29 additions & 9 deletions js/storage.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,59 @@
export const storage = (table) => {

/**
* @param {string=} key
* @returns {any}
*/
const get = (key = null) => {
const data = JSON.parse(localStorage.getItem(table));
return key ? data[String(key)] : data;
};

/**
* @param {string} key
* @param {any} value
* @returns {void}
*/
const set = (key, value) => {
let storage = get();
storage[String(key)] = value;
localStorage.setItem(table, JSON.stringify(storage));
let data = get();
data[String(key)] = value;
localStorage.setItem(table, JSON.stringify(data));
};

/**
* @param {string} key
* @returns {boolean}
*/
const has = (key) => Object.keys(get()).includes(String(key));

/**
* @param {string} key
* @returns {void}
*/
const unset = (key) => {
if (!has(key)) {
return;
}

let storage = get();
delete storage[String(key)];
localStorage.setItem(table, JSON.stringify(storage));
let data = get();
delete data[String(key)];
localStorage.setItem(table, JSON.stringify(data));
};

const clear = () => localStorage.setItem(table, JSON.stringify({}));
/**
* @returns {void}
*/
const clear = () => localStorage.setItem(table, '{}');

if (!localStorage.getItem(table)) {
clear();
}

return {
get,
set,
unset,
get,
has,
clear,
unset,
};
};

0 comments on commit 0c0bfad

Please sign in to comment.