Skip to content

Commit bd3a0cb

Browse files
author
Joe Previte
committed
refactor(heart): extract logic into heartbeatTimer fn
To make it easier to test, I extract heartbeatTimer into it's own function.
1 parent c35bf13 commit bd3a0cb

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

src/node/heart.ts

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,7 @@ export class Heart {
3333
if (typeof this.heartbeatTimer !== "undefined") {
3434
clearTimeout(this.heartbeatTimer)
3535
}
36-
this.heartbeatTimer = setTimeout(() => {
37-
this.isActive()
38-
.then((active) => {
39-
if (active) {
40-
this.beat()
41-
}
42-
})
43-
.catch((error) => {
44-
logger.warn(error.message)
45-
})
46-
}, this.heartbeatInterval)
36+
this.heartbeatTimer = setTimeout(async () => await heartbeatTimer(this.isActive, this.beat), this.heartbeatInterval)
4737
}
4838

4939
/**
@@ -55,3 +45,20 @@ export class Heart {
5545
}
5646
}
5747
}
48+
49+
/**
50+
* Helper function for the heartbeatTimer.
51+
*
52+
* If heartbeat is active, call beat. Otherwise do nothing.
53+
*
54+
* Extracted to make it easier to test.
55+
*/
56+
export async function heartbeatTimer(isActive: Heart["isActive"], beat: Heart["beat"]) {
57+
try {
58+
if (await isActive()) {
59+
beat()
60+
}
61+
} catch (error: unknown) {
62+
logger.warn((error as Error).message)
63+
}
64+
}

0 commit comments

Comments
 (0)