Skip to content

Commit e4d8904

Browse files
committed
Add: getUrlAddress
1 parent 5985670 commit e4d8904

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/lib/getUrlAddress.test.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { AddressInfo } from "net";
2+
import { getUrlAddress } from "./getUrlAddress";
3+
4+
5+
describe("getUrlAddress", () => {
6+
describe("when null is passed", () => {
7+
it("returns null", () => {
8+
const url = getUrlAddress(null);
9+
expect(url).toBeNull();
10+
});
11+
});
12+
13+
describe("when string is passed", () => {
14+
it("returns null", () => {
15+
const url = getUrlAddress("foobar");
16+
expect(url).toBeNull();
17+
});
18+
});
19+
20+
describe("when IPv4 is passed", () => {
21+
it("returns correct url", () => {
22+
const address: AddressInfo = {
23+
address: "0.0.0.0",
24+
family: "IPv4",
25+
port: 8888,
26+
}
27+
const url = getUrlAddress(address);
28+
expect(url).toEqual(`http://${address.address}:${address.port}`);
29+
});
30+
});
31+
32+
describe("when IPv6 is passed", () => {
33+
it("returns correct url", () => {
34+
const address: AddressInfo = {
35+
address: "::",
36+
family: "IPv6",
37+
port: 8888,
38+
}
39+
const url = getUrlAddress(address);
40+
expect(url).toEqual(`http://[${address.address}]:${address.port}`);
41+
});
42+
});
43+
});

src/lib/getUrlAddress.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { AddressInfo } from "net";
2+
3+
4+
export const getUrlAddress = (address: string | AddressInfo | null) => {
5+
if (!address || typeof address === "string") return null;
6+
7+
if (["IPv4", "IPv6"].indexOf(address.family) === -1) throw new Error("Unknown address family");
8+
9+
return `http://${address.family === "IPv4" ? address.address : `[${address.address}]`}:${address.port}`;
10+
}

0 commit comments

Comments
 (0)