passed/static/api.js

53 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-10-30 12:24:59 +00:00
/** Upload a password to the server
* @param {string} password Encryptes password
* @param {Promise<number>} expiresIn Number of seconds in which the password will expire
*/
async function uploadPassword(password, expiresIn) {
const res = await fetch("/api/password", {
method: "POST",
body: JSON.stringify({
password: password,
"expires-in": expiresIn,
}),
});
if (!res.ok) {
const msg = await res.text();
throw new Error(`Failed to upload password: ${res.status}: ${msg}`);
}
const json = await res.json();
return json.id;
}
/** Check if the server knows about the password
* @param {string} id Password ID
* @returns {Promise<bool>}
*/
async function hasPassword(id) {
const res = await fetch(`/api/password/${id}`, {
method: "HEAD",
});
if (res.status == 404) {
return false;
}
if (res.status == 204) {
return true;
}
throw new Error(`Failed to check if password exists: ${res.status}: ${msg}`);
}
/** Get a password from the server
* @param {string} id Password ID
* @returns {Promise<string>}
*/
async function getPassword(id) {
const res = await fetch(`/api/password/${id}`);
if (!res.ok) {
const msg = await res.text();
throw new Error(`Failed to get password: ${res.status}: ${msg}`);
}
const json = await res.json();
return json.password;
}