37 lines
1018 B
TypeScript
37 lines
1018 B
TypeScript
|
export const userId = (params: { username: string; database: string }) => {
|
||
|
const { username, database } = params;
|
||
|
const dbUrl = new URL(database);
|
||
|
return `@${username}>${dbUrl.hostname}`;
|
||
|
};
|
||
|
|
||
|
export const parseUserId = (id: string) => {
|
||
|
const matches = id.match(/^@([^>]+)>(.+)$/);
|
||
|
if (!matches) {
|
||
|
return null;
|
||
|
}
|
||
|
return { username: matches[1], database: matches[2] };
|
||
|
};
|
||
|
|
||
|
function hex2a(hex: string) {
|
||
|
var str = '';
|
||
|
for (var i = 0; i < hex.length; i += 2) {
|
||
|
var v = parseInt(hex.substr(i, 2), 16);
|
||
|
if (v) str += String.fromCharCode(v);
|
||
|
}
|
||
|
return str;
|
||
|
}
|
||
|
|
||
|
export const parseDbUrl = (urlString: string) => {
|
||
|
origin;
|
||
|
const url = new URL(urlString);
|
||
|
const match = url.pathname.match(/\/userdb-(.*)\//);
|
||
|
if (!match || match.length < 2) {
|
||
|
return { username: '', database: url.hostname };
|
||
|
}
|
||
|
const [_, encodedUser] = match;
|
||
|
return { username: hex2a(encodedUser), database: urlString };
|
||
|
};
|
||
|
|
||
|
export const dbUrlToUserId = (urlString: string) =>
|
||
|
userId(parseDbUrl(urlString));
|