unsplash / unsplash-js

🤖 Official JavaScript wrapper for the Unsplash API
https://www.npmjs.com/package/unsplash-js
MIT License
2.15k stars 157 forks source link

Can't set fetch agent #186

Closed juan-carvajal closed 3 years ago

juan-carvajal commented 3 years ago

Steps to Reproduce

-

import { createApi } from 'unsplash-js';
import fetch from 'node-fetch'
import { InitParams } from 'unsplash-js/dist/helpers/request';

const params: InitParams ={
  accessKey: "9R79Y48ZzMclksf3brbWZpQT8NbABgbmWe8gqyTwIso",
  fetch: fetch
}

Observed Behaviour

Image or video please.

Expected Behaviour

Technical Notes

OliverJAsh commented 3 years ago

For now you can workaround this using a type assertion, although it's far from ideal:

import nodeFetch from 'node-fetch'
import { InitParams } from 'unsplash-js/dist/helpers/request';

const params: InitParams ={
  accessKey: "abc",
  fetch: nodeFetch as unknown as typeof fetch
}

This boils down to the fact that nodeFetch is not assignable to fetch (as defined in lib.dom):

import nodeFetch from 'node-fetch'

/*
Type '(url: RequestInfo, init?: RequestInit) => Promise<Response>' is not assignable to type '(input: RequestInfo, init?: RequestInit) => Promise<Response>'.
  Types of parameters 'url' and 'input' are incompatible.
    Type 'RequestInfo' is not assignable to type 'import("/Users/oliverash/Development/unsplash-js-test/node_modules/node-fetch/@types/index").RequestInfo'.
      Type 'Request' is not assignable to type 'RequestInfo'.
        Type 'Request' is missing the following properties from type 'Request': size, buffer
*/
const myFetch: typeof fetch = nodeFetch;

fetch is defined in lib.dom, but since node-fetch is designed to be used in Node—not in the browser—we shouldn't be using lib.dom (related discussion).

The TS project needs to be configured to remove the dom lib. Even with this change, the issue will remain because of another issue with node-fetch whereby they pull in lib.dom: https://github.com/node-fetch/node-fetch/issues/1285.

Once that is fixed we should be able to do this:

import * as nodeFetch from 'node-fetch'
import { InitParams } from 'unsplash-js/dist/helpers/request';

declare global {
  var fetch: typeof nodeFetch.default;
  type RequestInit = nodeFetch.RequestInit;
  type Response = nodeFetch.Response;
}

const params: InitParams ={
  accessKey: "abc",
  fetch: nodeFetch.default
}
OliverJAsh commented 3 years ago

Closing as it's not an issue with this library as per the comment above.