feat: add user utils
This commit is contained in:
parent
b99bfabc23
commit
f8278e3b35
59
src/user_utils.ts
Normal file
59
src/user_utils.ts
Normal file
|
@ -0,0 +1,59 @@
|
||||||
|
/** User login format of cohabit `firstname`.`lastname`. */
|
||||||
|
export type User = `${string}.${string}`
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform a {@link UserDomain} into a {@link User}.
|
||||||
|
*
|
||||||
|
* @param userDomain User domain (hostname subdomain) derived from user login.
|
||||||
|
* @returns Corresponding user user login.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* import { toUser } from './user_utils.ts'
|
||||||
|
*
|
||||||
|
* const user = toUser('john-doe')
|
||||||
|
* console.assert(user === 'john.doe')
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function toUser(userDomain: UserDomain): User {
|
||||||
|
//TODO check is user in cohabit.ressources.users
|
||||||
|
return userDomain.replace('-', '.') as User
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User personal portfolio domain rerived from cohabit user login
|
||||||
|
* as `firstname`-`lastname`.
|
||||||
|
*/
|
||||||
|
export type UserDomain = `${string}-${string}`
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check hostname subdomain against {@link UserDomain}.
|
||||||
|
*
|
||||||
|
* @param userDomain Hostname to assert.
|
||||||
|
* @returns Asserted user domain.
|
||||||
|
*
|
||||||
|
* @example Valid user domain
|
||||||
|
* ```ts
|
||||||
|
* import { toUserDomain } from './user_utils.ts'
|
||||||
|
*
|
||||||
|
* const userDomain = toUserDomain('john-doe')
|
||||||
|
* console.assert(userDomain === 'john-doe')
|
||||||
|
* ```
|
||||||
|
* @example Invalid user domain
|
||||||
|
* ```ts
|
||||||
|
* import { toUserDomain } from './user_utils.ts'
|
||||||
|
*
|
||||||
|
* try {
|
||||||
|
* const userDomain = toUserDomain('johndont')
|
||||||
|
* } catch (error) {
|
||||||
|
* console.assert(error instanceof Error)
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function toUserDomain(userDomain: string): UserDomain {
|
||||||
|
//TODO check is user in cohabit.ressources.users
|
||||||
|
if (/\w+-\w+/.test(userDomain)) {
|
||||||
|
return userDomain as UserDomain
|
||||||
|
}
|
||||||
|
throw new TypeError(`invalid user login (${userDomain.replace('-', '.')})`)
|
||||||
|
}
|
Loading…
Reference in a new issue