@@ -33,9 +33,11 @@ type PushService struct {
3333
3434type PushServiceConfig struct {
3535 CredentialsJSON string
36+ Debounce time.Duration
3637 Timeout time.Duration
3738}
3839
40+ // NewPushService creates a new PushService.
3941func NewPushService (params PushServiceParams ) * PushService {
4042 if params .Config .Timeout == 0 {
4143 params .Config .Timeout = time .Second
@@ -48,7 +50,7 @@ func NewPushService(params PushServiceParams) *PushService {
4850 }
4951}
5052
51- // init
53+ // init initializes the FCM client.
5254func (s * PushService ) init (ctx context.Context ) (err error ) {
5355 s .mux .Lock ()
5456 defer s .mux .Unlock ()
@@ -71,6 +73,7 @@ func (s *PushService) init(ctx context.Context) (err error) {
7173 return
7274}
7375
76+ // sendAll sends messages to all targets from the cache after initializing the service.
7477func (s * PushService ) sendAll (ctx context.Context ) {
7578 if err := s .init (ctx ); err != nil {
7679 s .Logger .Error ("Can't init push service" , zap .Error (err ))
@@ -92,6 +95,7 @@ func (s *PushService) sendAll(ctx context.Context) {
9295 }
9396}
9497
98+ // sendSingle sends a single message to the specified token
9599func (s * PushService ) sendSingle (ctx context.Context , token string , data map [string ]string ) error {
96100 _ , err := s .client .Send (ctx , & messaging.Message {
97101 Data : data ,
@@ -104,8 +108,13 @@ func (s *PushService) sendSingle(ctx context.Context, token string, data map[str
104108 return err
105109}
106110
111+ // Run runs the service with the provided context if a debounce is set.
107112func (s * PushService ) Run (ctx context.Context ) {
108- ticker := time .NewTicker (time .Second )
113+ if s .Config .Debounce == 0 {
114+ return
115+ }
116+
117+ ticker := time .NewTicker (s .Config .Debounce )
109118 defer ticker .Stop ()
110119
111120 for {
@@ -118,8 +127,13 @@ func (s *PushService) Run(ctx context.Context) {
118127 }
119128}
120129
130+ // Enqueue adds the data to the cache and immediately sends all messages if the debounce is 0.
121131func (s * PushService ) Enqueue (ctx context.Context , token string , data map [string ]string ) error {
122132 s .cache .Set (token , data )
123133
134+ if s .Config .Debounce == 0 {
135+ s .sendAll (ctx )
136+ }
137+
124138 return nil
125139}
0 commit comments