settings: set avatar

This commit is contained in:
Flummi 2022-03-28 17:32:00 +02:00
parent cf1606884a
commit b19c24727a
3 changed files with 78 additions and 2 deletions

View File

@ -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);
});
}
})();

View File

@ -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;
};

View File

@ -1,6 +1,6 @@
@include(snippets/header)
<h1>Settings</h1>
@if(session.avatar)<a href="//f0ck.me/{{ session.avatar }}"><img src="/t/{{ session.avatar }}.webp" /></a>@endif
@if(session.avatar)<a href="//f0ck.me/{{ session.avatar }}"><img id="img_avatar" src="/t/{{ session.avatar }}.webp" /></a>@endif
<h2>Account</h2>
<table class="table">
<tbody>
@ -18,7 +18,7 @@
</tr>
<tr>
<td>avatar</td>
<td><input type="text" class="input" value="{{ session.avatar }}" /><input type="submit" value="save" /></td>
<td><input type="text" class="input" name="i_avatar" value="{{ session.avatar }}" /><input type="submit" id="s_avatar" value="save" /></td>
</tr>
</tbody>
</table>