WordPress / gutenberg

The Block Editor project for WordPress and beyond. Plugin is available from the official repository.
https://wordpress.org/gutenberg/
Other
10.41k stars 4.16k forks source link

@wordpress/api-fetch remove window dependency to support node env #17551

Open isBatak opened 5 years ago

isBatak commented 5 years ago

I'm trying to use @wordpress/api-fetch on node (decoupled WordPress and SSR), but it is not easy to polyfill fetch because of window.fetch usage https://github.com/WordPress/gutenberg/blob/master/packages/api-fetch/src/index.js#L161 and I don't want to reimplement whole defaultFetchHandler logic with setFetchHandler solution. I just want to replace fetch with something else like isomorphic-fetch.

Solution:

isBatak commented 5 years ago

@swissspidy I'm planning to make a PR for this feature, this is the idea https://github.com/isBatak/gutenberg/commit/72e35056c2dda55d46092380f16b349892dfa3b2 for the API. But, now tests are failing and I have no idea how to fix them. Do you have any suggestion?

swissspidy commented 5 years ago

Well which tests are failing...? If you'd create the PR already then you could point to the failing tests on Travis CI and more easily get technical feedback from maintainers.

isBatak commented 5 years ago

I'll make a PR now, and see what will happen :D

talldan commented 4 years ago

The PR #17574 seems to have plenty of technical feedback, so I'm removing that label.

Also removing In Progress, since the PR hasn't had recent updates.

hypest commented 4 years ago

FYI, added this to the "Mobile Apps" project board to cover the apps side of the issue.

iamandrewluca commented 4 years ago

Besides this solutions

another solution would be to export a factory function

import { createApiFetch } from '@wordpress/api-fetch'

// Browser
const apiFetch = createApiFetch({ fetch: window.fetch })

// Node
const apiFetch = createApiFetch({ fetch: require('node-fetch') })

My workaround

import fetch from 'node-fetch'
global.window = { fetch }
import apiFetch from '@wordpress/api-fetch'

apiFetch({ path: '/wp-json/wp/v2/users' }).then(console.log)