@donation-alerts/common
Version:
Common utils and types that are used in other @donation-alerts packages.
35 lines (34 loc) • 1.05 kB
JavaScript
const NUMERIC_STRING_REGEX = /^\d+$/u;
/**
* Extracts the user ID from an argument that is possibly an object containing that ID.
*
* @param user The user ID or object.
*/
export function extractUserId(user) {
if (typeof user === 'number') {
return user;
}
else if (typeof user === 'string') {
if (NUMERIC_STRING_REGEX.test(user)) {
return parseInt(user, 10);
}
throw new TypeError('User ID must be integer or numeric string');
}
else {
if (typeof user.id === 'number') {
return user.id;
}
if (NUMERIC_STRING_REGEX.test(user.id)) {
return parseInt(user.id, 10);
}
throw new TypeError('User ID must be integer or numeric string');
}
}
/**
* Extracts the username from an argument that is possibly an object containing that name.
*
* @param user The username or object containing `name` field with username.
*/
export function extractUserName(user) {
return typeof user === 'string' ? user : user.name;
}