phrase/phrase-js

Using phrase with node.js breaks googleapis

closingin opened this issue ยท 1 comments

Hello there ๐Ÿ‘‹

I'm currently using both PhraseJS and the Google Drive API in a node.js application, and based on my tests with the README recommendations, these two packages are incompatible.

The problem lies in the way that Phrase works in node.js environments, which is requiring the window object to be defined for the fetch integration.

Google APIs don't work the same depending on whether you're using a browser or not, and they check the window object to know that. Note that checking this object is the "normal" way to differentiate runtime environments.

I guess that you recommend to override the window object because you don't want to handle different runtime environments manually, but I think there is another way to make the package work on node.js.

From reading the project codebase, I found out that we can pass a fetchApi property to the BaseAPI constructor, which overrides the default one, and I can confirm that it works pretty well.

Node < v18 workaround :

import FormData from 'form-data'
import fetch from 'node-fetch'

import {
  Configuration,
  KeysApi
} from 'phrase-js'

const globalAny = global;
globalAny.FormData = FormData

const configuration = new Configuration({
  apiKey: '<your-api-key>',
  fetchApi: fetch
})
const keysApi = new KeysApi(configuration)

Node >= v18 compatible workaround (the fetch api and FormData have been implemented in node 18.) :

import {
  Configuration,
  KeysApi
} from 'phrase-js'

const configuration = new Configuration({
  apiKey: '<your-api-key>',
  fetchApi: fetch
})
const keysApi = new KeysApi(configuration)

Do you think that you could do something about it? Actually, I think that just updating the documentation with a disclaimer and a new snippet could be enough.

Best!

Hi @closingin ๐Ÿ‘‹. Thanks for this really detailed investigation! This is really helpful feedback and I'll try to make sure that the documentation is properly adapted