diff --git a/public/s/js/admin.js b/public/s/js/admin.js index 83ed61b..da36bc1 100644 --- a/public/s/js/admin.js +++ b/public/s/js/admin.js @@ -347,4 +347,37 @@ const flash = ({ type, msg }) => { toggleFavEvent(); }); } + + if(document.location.pathname === '/settings') { + const saveAvatar = async e => { + e.preventDefault(); + + const avatar = +document.querySelector('input[name="i_avatar"]').value; + let res = await fetch('/api/v2/settings/setAvatar', { + method: 'PUT', + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ avatar }) + }); + const code = res.status; + res = await res.json(); + + switch(code) { + case 200: + document.querySelector('#img_avatar').src = `/t/${avatar}.webp`; + document.querySelector('img.avatar').src = `/t/${avatar}.webp`; + break; + default: + console.log(res); + break; + } + }; + + document.querySelector('input#s_avatar').addEventListener('click', saveAvatar); + document.querySelector('input[name="i_avatar"]').addEventListener('keyup', async e => { + if(e.key === 'Enter') + await saveAvatar(e); + }); + } })(); diff --git a/src/inc/routes/apiv2/settings.mjs b/src/inc/routes/apiv2/settings.mjs new file mode 100644 index 0000000..764f06f --- /dev/null +++ b/src/inc/routes/apiv2/settings.mjs @@ -0,0 +1,43 @@ +import sql from '../../sql.mjs'; +import lib from '../../lib.mjs'; + +export default router => { + router.group(/^\/api\/v2\/settings/, group => { + group.put(/\/setAvatar/, lib.auth, async (req, res) => { + if(!req.post.avatar) { + return res.json({ + msg: 'no avatar provided', + debug: req.post + }, 400); // bad request + } + + const avatar = +req.post.avatar; + + const itemid = ( + await sql('items') + .select('id') + .where('id', avatar) + )?.[0]?.id; + + if(!itemid) { + return res.json({ + msg: 'itemid not found' + }, 404); // not found + } + + const q = await sql('user_options') + .update({ + avatar + }) + .where('user_id', req.session.id); + + return res.json({ + msg: q + }, 200); + }); + + return group; + }); + + return router; +}; diff --git a/views/settings.html b/views/settings.html index 498286d..bb23e0b 100644 --- a/views/settings.html +++ b/views/settings.html @@ -1,6 +1,6 @@ @include(snippets/header)

Settings

-@if(session.avatar)@endif +@if(session.avatar)@endif

Account

@@ -18,7 +18,7 @@ - +
avatar