Skip to content

Commit dbc6831

Browse files
committed
Simplify time logic for tutorial
1 parent 1c1d0b1 commit dbc6831

File tree

1 file changed

+16
-30
lines changed

1 file changed

+16
-30
lines changed

howtos/how-to-set-an-away-message/server.js

+16-30
Original file line numberDiff line numberDiff line change
@@ -12,29 +12,21 @@ app.listen(3000, () => console.log("Server is up"));
1212
// Track when we auto-replied to each conversation ID so we don't send multiple replies in a row
1313
const alreadyReplied = {};
1414

15-
// Start and end of support hours in "HH:mm:ss" format
16-
const startTime = "09:00:00";
17-
const endTime = "17:00:00";
18-
19-
function isTimeBetween(start, end, check) {
20-
if (start <= end) {
21-
return check >= start && check <= end;
22-
} else {
23-
// window overlaps midnight
24-
return (
25-
(check >= start && check <= "23:59:59") ||
26-
(check >= "00:00:00" && check <= end)
27-
);
28-
}
29-
}
15+
function isOutOfHours(date) {
16+
// Sunday
17+
if (date.getDay() === 0) return true;
18+
19+
// Saturday
20+
if (date.getDay() === 6) return true;
21+
22+
// Before 9am
23+
if (date.getHours() < 12) return true;
3024

31-
// Convert timestamp to "HH:mm:ss" format
32-
function timeStampToTime(timestamp) {
33-
const checkDate = new Date(timestamp);
34-
const hours = "0" + checkDate.getHours();
35-
const minutes = "0" + checkDate.getMinutes();
36-
const seconds = "0" + checkDate.getSeconds();
37-
return hours.slice(-2) + ":" + minutes.slice(-2) + ":" + seconds.slice(-2);
25+
// After 5pm
26+
if (date.getHours() >= 17) return true;
27+
28+
// Otherwise
29+
return false;
3830
}
3931

4032
async function sendReply(conversationId) {
@@ -63,15 +55,9 @@ app.post("/talkjs", async (req, res) => {
6355
const conversationId = data.conversation.id;
6456

6557
const role = data.sender?.role;
66-
const timestamp = data.message.createdAt;
67-
68-
const outOfOffice = !isTimeBetween(
69-
startTime,
70-
endTime,
71-
timeStampToTime(timestamp)
72-
);
58+
const date = new Date(data.message.createdAt);
7359

74-
if (outOfOffice && role === "customer") {
60+
if (isOutOfHours(date) && role === "customer") {
7561
if (!(conversationId in alreadyReplied)) {
7662
await sendReply(conversationId);
7763
}

0 commit comments

Comments
 (0)