@@ -9,27 +9,25 @@ const toUrlSearchParams = require('../lib/to-url-search-params')
9
9
10
10
module . exports = configure ( ( api , options ) => {
11
11
const subsTracker = SubscriptionTracker . singleton ( )
12
- const publish = require ( './publish' ) ( options )
13
12
14
- return async ( topic , handler , options = { } ) => {
13
+ return async ( topic , handler , options = { } ) => { // eslint-disable-line require-await
15
14
options . signal = subsTracker . subscribe ( topic , handler , options . signal )
16
15
17
- let res
16
+ let done
17
+ let fail
18
+
19
+ const result = new Promise ( ( resolve , reject ) => {
20
+ done = resolve
21
+ fail = reject
22
+ } )
18
23
19
24
// In Firefox, the initial call to fetch does not resolve until some data
20
- // is received. If this doesn't happen within 1 second send an empty message
21
- // to kickstart the process.
22
- const ffWorkaround = setTimeout ( async ( ) => {
23
- log ( `Publishing empty message to "${ topic } " to resolve subscription request` )
24
- try {
25
- await publish ( topic , new Uint8Array ( 0 ) , options )
26
- } catch ( err ) {
27
- log ( 'Failed to publish empty message' , err )
28
- }
29
- } , 1000 )
25
+ // is received. If this doesn't happen within 1 second assume success
26
+ const ffWorkaround = setTimeout ( ( ) => done ( ) , 1000 )
30
27
31
- try {
32
- res = await api . post ( 'pubsub/sub' , {
28
+ // Do this async to not block Firefox
29
+ setTimeout ( ( ) => {
30
+ api . post ( 'pubsub/sub' , {
33
31
timeout : options . timeout ,
34
32
signal : options . signal ,
35
33
searchParams : toUrlSearchParams ( {
@@ -38,18 +36,31 @@ module.exports = configure((api, options) => {
38
36
} ) ,
39
37
headers : options . headers
40
38
} )
41
- } catch ( err ) { // Initial subscribe fail, ensure we clean up
42
- subsTracker . unsubscribe ( topic , handler )
43
- throw err
44
- }
39
+ . catch ( ( err ) => {
40
+ // Initial subscribe fail, ensure we clean up
41
+ subsTracker . unsubscribe ( topic , handler )
45
42
46
- clearTimeout ( ffWorkaround )
43
+ fail ( err )
44
+ } )
45
+ . then ( ( response ) => {
46
+ clearTimeout ( ffWorkaround )
47
47
48
- readMessages ( res . ndjson ( ) , {
49
- onMessage : handler ,
50
- onEnd : ( ) => subsTracker . unsubscribe ( topic , handler ) ,
51
- onError : options . onError
52
- } )
48
+ if ( ! response ) {
49
+ // if there was no response, the subscribe failed
50
+ return
51
+ }
52
+
53
+ readMessages ( response . ndjson ( ) , {
54
+ onMessage : handler ,
55
+ onEnd : ( ) => subsTracker . unsubscribe ( topic , handler ) ,
56
+ onError : options . onError
57
+ } )
58
+
59
+ done ( )
60
+ } )
61
+ } , 0 )
62
+
63
+ return result
53
64
}
54
65
} )
55
66
0 commit comments