feat(utils): add parseElectrumUrl util

This commit is contained in:
Marek Polak
2023-08-16 16:10:22 +02:00
committed by martin
parent 6198ff0652
commit 61dce520d4
3 changed files with 42 additions and 0 deletions

View File

@@ -22,6 +22,7 @@ export * from './isNotUndefined';
export * from './isUrl';
export * from './mergeDeepObject';
export * from './objectPartition';
export * from './parseElectrumUrl';
export * from './parseHostname';
export * from './promiseAllSequence';
export * from './redactUserPath';

View File

@@ -0,0 +1,12 @@
// URL is in format host:port:[t|s] (t for tcp, s for ssl)
const ELECTRUM_URL_REGEX = /^(?:([a-zA-Z0-9.-]+)|\[([a-f0-9:]+)\]):([0-9]{1,5}):([ts])$/;
export const parseElectrumUrl = (url: string) => {
const match = url.match(ELECTRUM_URL_REGEX);
if (!match) return undefined;
return {
host: match[1] ?? match[2],
port: Number.parseInt(match[3], 10),
protocol: match[4] as 't' | 's',
};
};

View File

@@ -0,0 +1,29 @@
import { parseElectrumUrl } from '../src/parseElectrumUrl';
const FIXTURE = [
['electrum.example.com:50001:t', 'electrum.example.com', 50001, 't'],
['electrum.example.com:50001:s', 'electrum.example.com', 50001, 's'],
['electrum.example.onion:50001:t', 'electrum.example.onion', 50001, 't'],
['electrum.example.com:50001:x'],
['127.0.0.1:50001:t', '127.0.0.1', 50001, 't'],
['2001:0db8:85a3:0000:0000:8a2e:0370:7334:50001:t'],
[
'[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:50001:t',
'2001:0db8:85a3:0000:0000:8a2e:0370:7334',
50001,
't',
],
['[::1]:50001:t', '::1', 50001, 't'],
['[example.com]:50001:t'],
['wss://blockfrost.io'],
['https://google.com'],
[''],
] as const;
describe('parseElectrumUrl', () => {
FIXTURE.forEach(([url, host, port, protocol]) =>
it(url, () => {
expect(parseElectrumUrl(url)).toStrictEqual(host && { host, port, protocol });
}),
);
});