diff --git a/.changeset/slow-seas-lead.md b/.changeset/slow-seas-lead.md new file mode 100644 index 0000000..5e673b9 --- /dev/null +++ b/.changeset/slow-seas-lead.md @@ -0,0 +1,5 @@ +--- +"@ecoflow-api/rest-client": patch +--- + +add host URL validation diff --git a/packages/rest-client/src/lib/RestClient.test.ts b/packages/rest-client/src/lib/RestClient.test.ts new file mode 100644 index 0000000..8d265d7 --- /dev/null +++ b/packages/rest-client/src/lib/RestClient.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "@jest/globals"; +import { RestClient } from "./RestClient"; + +describe("RestClient", () => { + const createClient = (host: string) => + new RestClient({ + accessKey: "test-access-key", + secretKey: "test-secret-key", + host, + }); + + it("should construct successfully with a valid https host", () => { + expect(() => createClient("https://api-e.ecoflow.com")).not.toThrow(); + }); + + it("should construct successfully with a valid http host", () => { + expect(() => createClient("http://localhost:3000")).not.toThrow(); + }); + + it("should throw an error with an invalid host URL", () => { + expect(() => createClient("invalid-url")).toThrow("Invalid host URL"); + }); + + it("should throw an error with an invalid protocol", () => { + expect(() => createClient("sftp://api.ecoflow.com")).toThrow( + "Invalid host protocol: http or https expected", + ); + }); + + it("should throw an error with an empty host", () => { + expect(() => createClient("")).toThrow("Invalid host URL"); + }); +}); diff --git a/packages/rest-client/src/lib/RestClient.ts b/packages/rest-client/src/lib/RestClient.ts index 98c1a2d..41ab8fe 100644 --- a/packages/rest-client/src/lib/RestClient.ts +++ b/packages/rest-client/src/lib/RestClient.ts @@ -100,6 +100,15 @@ export class RestClient { * @constructor */ constructor(opts: RestClientOptions) { + const parsed = URL.parse(opts.host); + if (!parsed) { + throw new Error(`Invalid host URL`); + } + + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error(`Invalid host protocol: http or https expected`); + } + const generateUrl = (path: string) => `${opts.host}${path}`; this.requestHandler = new RequestHandler(