Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion defaultmodules/weather/node_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ module.exports = NodeHelper.create({
});

// Start periodic fetching
provider.start();
provider.start(config.initialLoadDelay);

Log.log(`Weather provider ${identifier} initialized for instance ${instanceId}`);
} catch (error) {
Expand Down
9 changes: 6 additions & 3 deletions defaultmodules/weather/weatherprovider.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ class WeatherProvider {
this.onErrorCallback = onError;
}

/** Start periodic fetching. */
start () {
this.fetcher?.startPeriodicFetch();
/**
* Start periodic fetching.
* @param {number} [initialDelay] - Delay before the first fetch in ms
*/
start (initialDelay = 0) {
this.fetcher?.startPeriodicFetch(initialDelay);
}

/** Stop periodic fetching. */
Expand Down
11 changes: 9 additions & 2 deletions js/http_fetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,16 @@ class HTTPFetcher extends EventEmitter {

/**
* Starts periodic fetching
* @param {number} [initialDelay] - Delay before the first fetch in ms
*/
startPeriodicFetch () {
this.fetch();
startPeriodicFetch (initialDelay = 0) {
this.clearTimer();

if (initialDelay > 0) {
this.reloadTimer = setTimeout(() => this.fetch(), initialDelay);
} else {
this.fetch();
}
}

/**
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/functions/http_fetcher_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,25 @@ describe("HTTPFetcher", () => {
expect(text).toBe(responseData);
});

it("should delay the first fetch when an initial delay is configured", async () => {
vi.useFakeTimers();
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("test data")
);
fetcher = new HTTPFetcher(TEST_URL, { reloadInterval: 60000 });

fetcher.startPeriodicFetch(15000);

expect(fetchSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(14999);
expect(fetchSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(fetchSpy).toHaveBeenCalledTimes(1);

fetchSpy.mockRestore();
vi.useRealTimers();
});

it("should emit error event on network failure", async () => {
server.use(
http.get(TEST_URL, () => {
Expand Down