Skip to content

Commit

Permalink
fix: websocket and fetch fix for browser (#291)
Browse files Browse the repository at this point in the history
* fix: fetch & websocket browser support

Signed-off-by: blu3beri <[email protected]>

* fix: websocket and fetch typings

Signed-off-by: blu3beri <[email protected]>

* fix: use typings from global.fetch and global.ws

Signed-off-by: blu3beri <[email protected]>
  • Loading branch information
berendsliedrecht authored May 21, 2021
1 parent 7bbf7eb commit 84e570d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
6 changes: 5 additions & 1 deletion src/utils/environment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export function isNodeJS() {
return typeof process !== 'undefined' && process.release.name === 'node'
return typeof process !== 'undefined' && process.release && process.release.name === 'node'
}

export function isReactNative() {
return typeof navigator != 'undefined' && navigator.product == 'ReactNative'
}
23 changes: 16 additions & 7 deletions src/utils/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
import { isNodeJS } from './environment'
import { isNodeJS, isReactNative } from './environment'

// RN exposes global fetch
let fetch = global.fetch
let Headers = global.Headers
let Request = global.Request
let Response = global.Response
let fetch: typeof global.fetch
let Headers
let Request
let Response

// NodeJS doesn't have fetch by default
if (!fetch && isNodeJS()) {
if (isNodeJS()) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nodeFetch = require('node-fetch')

fetch = nodeFetch.default
Headers = nodeFetch.Headers
Request = nodeFetch.Request
Response = nodeFetch.Response
} else if (isReactNative()) {
fetch = global.fetch
Headers = global.Headers
Request = global.Request
Response = global.Response
} else {
fetch = window.fetch.bind(window)
Headers = window.Headers
Request = window.Request
Response = window.Response
}

export { fetch, Headers, Request, Response }
11 changes: 7 additions & 4 deletions src/utils/ws.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { isNodeJS } from './environment'
import { isNodeJS, isReactNative } from './environment'

// RN exposes global WebSocket
let WebSocket = global.WebSocket
let WebSocket: typeof global.WebSocket

// NodeJS doesn't have WebSocket by default
if (!WebSocket && isNodeJS()) {
if (isNodeJS()) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nodeWebSocket = require('ws')

WebSocket = nodeWebSocket
} else if (isReactNative()) {
WebSocket = global.WebSocket
} else {
WebSocket = window.WebSocket.bind(window)
}

export { WebSocket }

0 comments on commit 84e570d

Please sign in to comment.