quickSnote
This commit is contained in:
57
browser-extension/background.js
Normal file
57
browser-extension/background.js
Normal file
@@ -0,0 +1,57 @@
|
||||
let serverUrl = '';
|
||||
|
||||
browser.storage.sync.get('serverUrl').then(r => {
|
||||
if (r.serverUrl) serverUrl = r.serverUrl.replace(/\/+$/, '');
|
||||
});
|
||||
|
||||
browser.storage.onChanged.addListener(changes => {
|
||||
if (changes.serverUrl) {
|
||||
serverUrl = changes.serverUrl.newValue.replace(/\/+$/, '');
|
||||
}
|
||||
});
|
||||
|
||||
browser.runtime.onMessage.addListener((msg, sender) => {
|
||||
switch (msg.kind) {
|
||||
case 'list_users':
|
||||
return listUsers();
|
||||
case 'save_note':
|
||||
return saveNote(msg);
|
||||
default:
|
||||
return Promise.reject(new Error('Unknown message kind'));
|
||||
}
|
||||
});
|
||||
|
||||
async function request(path, opts) {
|
||||
if (!serverUrl) throw new Error('Server URL not configured');
|
||||
opts = opts || {};
|
||||
opts.credentials = 'include';
|
||||
const res = await fetch(serverUrl + path, opts);
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.detail || 'HTTP ' + res.status);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async function listUsers() {
|
||||
const users = await request('/api/users', { headers: { 'Accept': 'application/json' } });
|
||||
return { users: users };
|
||||
}
|
||||
|
||||
async function saveNote(msg) {
|
||||
const body = { body: msg.body };
|
||||
if (msg.username) body.username = msg.username;
|
||||
|
||||
if (msg.id) {
|
||||
return request('/api/notes/' + msg.id, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
return request('/api/notes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user