passed/static/js/api.js
2024-11-10 10:46:40 +01:00

54 lines
1.3 KiB
JavaScript

/** Upload a password to the server
* @param {string} password Encryptes password
* @param {number} expiresIn Number of seconds in which the password will expire
* @returns {Promise<string>}
*/
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;
}