feathermost/js/util.js
Midgard 596cd63fb5
Make Client remember its token, add ID form checks
Refactor MattermostClient, deduplicating code and making it remember its token.

Make functions that ask for a Mattermost ID check that they get
something of the correct form.
2020-03-31 18:13:02 +02:00

68 lines
1.6 KiB
JavaScript

/**
* Return an endpoint URL that has a protocol, domain and path
*/
function normalizedEndpoint(endpoint) {
let matches = endpoint.match(/^(https?:\/\/)?([^\/]+)(\/.*)?$/i);
if (!matches) throw Error("Invalid endpoint URL");
let protocol = matches[1] || "https://";
let domain = matches[2];
let path = matches[3] || "/api/v4";
return `${protocol}${domain}${path}`;
}
/**
* Return the endpoint as it should be shown to the user
*/
function humanReadableEndpoint(endpoint) {
let matches = endpoint.match(/^(https?:\/\/.+)\/api\/v4$/i);
if (!matches) throw Error("Invalid endpoint URL");
return matches[1];
}
/**
* Shorthand for document.getElementById
*/
function byId(id, nullOk=false) {
const el = document.getElementById(id);
if (!el && !nullOk) {
console.error(`No element #${id}`);
}
return el;
}
/**
* Wrap a function so that it receives `this` as first argument
*/
function thisToArg(f) {
return function(...rest) {
return f(this, ...rest);
}
}
class AssertionError extends Error {}
/**
* Throw an AssertionError if the first argument is not true
*/
function assert(condition, message) {
if (!condition) {
if (message) {
throw new AssertionError(`Assertion failed: ${message}`);
} else {
throw new AssertionError("Assertion failed");
}
}
}
const MATTERMOST_ID_REGEXP = /^[a-z0-9]{26}$/;
function assertIsMattermostId(string, name="") {
assert(MATTERMOST_ID_REGEXP.test(string), `${name} has the form of a Mattermost ID`);
}
function assertIsNullOrMattermostId(string, name="") {
assert(string === null || MATTERMOST_ID_REGEXP.test(string), `${name} is null or has the form of a Mattermost ID`);
}