3434// -START pubsub_close_subscription_with_timeout]
3535
3636// Imports the Google Cloud client library
37- const { PubSub, Duration} = require ( '@google-cloud/pubsub' ) ;
37+ const {
38+ PubSub,
39+ Duration,
40+ SubscriptionCloseBehaviors,
41+ } = require ( '@google-cloud/pubsub' ) ;
3842
3943// Creates a client; cache this for further use
4044const pubsub = new PubSub ( ) ;
@@ -45,17 +49,34 @@ async function closeSubscriptionWithTimeout(
4549) {
4650 const topic = pubsub . topic ( topicNameOrId ) ;
4751
48- const timeout = Duration . from ( { seconds : 10 } ) ;
49- const zeroTimeout = Duration . from ( { seconds : 0 } ) ;
50-
5152 // Closes the subscription immediately, not waiting for anything.
52- let subscription = topic . subscription ( subscriptionNameOrId ) ;
53- await subscription . close ( { timeout : zeroTimeout } ) ;
53+ let subscription = topic . subscription ( subscriptionNameOrId , {
54+ closeOptions : {
55+ timeout : Duration . from ( { seconds : 0 } ) ,
56+ } ,
57+ } ) ;
58+ await subscription . close ( ) ;
5459
55- // Shuts down the gRPC connection, sends nacks for buffered messages,
56- // and closes the subscription after a set timeout.
57- subscription = topic . subscription ( subscriptionNameOrId ) ;
58- await subscription . close ( { timeout} ) ;
60+ // Shuts down the gRPC connection, and waits for just before the timeout
61+ // to send nacks for buffered messages. If `timeout` were missing, this
62+ // would wait for the maximum leasing timeout.
63+ subscription = topic . subscription ( subscriptionNameOrId , {
64+ closeOptions : {
65+ behavior : SubscriptionCloseBehaviors . WaitForProcessing ,
66+ timeout : Duration . from ( { seconds : 10 } ) ,
67+ } ,
68+ } ) ;
69+ await subscription . close ( ) ;
70+
71+ // Shuts down the gRPC connection, sends nacks for buffered messages, and waits
72+ // through the timeout for nacks to send.
73+ subscription = topic . subscription ( subscriptionNameOrId , {
74+ closeOptions : {
75+ behavior : SubscriptionCloseBehaviors . NackImmediately ,
76+ timeout : Duration . from ( { seconds : 10 } ) ,
77+ } ,
78+ } ) ;
79+ await subscription . close ( ) ;
5980}
6081// -END pubsub_close_subscription_with_timeout]
6182
0 commit comments