Skip to content

Commit 27cc8ad

Browse files
techwritermatclaude
andcommitted
Wire the automated polling trigger to the poll it opens
The three snippets in this file demonstrated the pieces of a poll service separately, so the trigger handler only logged and never opened a poll. The tutorial that embeds them describes one running service, which left the page claiming output the code could not produce. Reorder the file so the poll template and the cooldown guard come first, then have the trigger handler call them. The cooldown guard now logs when it blocks a trigger, which is the case the tutorial asks the reader to observe. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent fe1a5e7 commit 27cc8ad

1 file changed

Lines changed: 18 additions & 17 deletions

File tree

docs-snippets/use-cases/automated-polling.ts

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,6 @@ const pubnub = new PubNub({
66
userId: 'poll-service',
77
});
88

9-
// snippet.automatedPollingReceiveTrigger
10-
type PollTrigger = { reaction: string };
11-
12-
const triggerSubscription = pubnub.channel('game.poll-triggers').subscription({ receivePresenceEvents: false });
13-
14-
triggerSubscription.onMessage = (event) => {
15-
const trigger = event.message as PollTrigger;
16-
17-
console.log('open a poll because fans keep tapping', trigger.reaction);
18-
};
19-
20-
triggerSubscription.subscribe();
21-
// snippet.end
22-
239
// snippet.automatedPollingPublishTriggeredPoll
2410
const pollsByReaction: Record<string, { title: string; options: { id: number; text: string }[] }> = {
2511
'\u{1F621}': {
@@ -67,8 +53,6 @@ async function openPollForReaction(reaction: string) {
6753
);
6854
}
6955
}
70-
71-
await openPollForReaction('\u{1F621}');
7256
// snippet.end
7357

7458
// snippet.automatedPollingThrottleTriggers
@@ -79,12 +63,29 @@ function shouldOpenPoll() {
7963
const now = Date.now();
8064

8165
if (now - lastPollOpenedAt < minimumMillisecondsBetweenPolls) {
66+
console.log('that trigger arrived inside the cooldown window, so no new poll opened');
8267
return false;
8368
}
8469

8570
lastPollOpenedAt = now;
8671
return true;
8772
}
73+
// snippet.end
74+
75+
// snippet.automatedPollingReceiveTrigger
76+
type PollTrigger = { reaction: string };
8877

89-
console.log('open a poll now?', shouldOpenPoll());
78+
const triggerSubscription = pubnub.channel('game.poll-triggers').subscription({ receivePresenceEvents: false });
79+
80+
triggerSubscription.onMessage = (event) => {
81+
const trigger = event.message as PollTrigger;
82+
83+
console.log('open a poll because fans keep tapping', trigger.reaction);
84+
85+
if (shouldOpenPoll()) {
86+
void openPollForReaction(trigger.reaction);
87+
}
88+
};
89+
90+
triggerSubscription.subscribe();
9091
// snippet.end

0 commit comments

Comments
 (0)