3

I have node-fetch installed, but the rest of the files in the project aren't importing it and the tests for them aren't failing

import { IQuery } from 'models/IQuery.interface';
import { NextApiRequest, NextApiResponse } from 'next';
import { handleProxyResponse } from 'utils/handleProxyResponse.util';
import { appendApiRoute, getDefaultHeaders, getLocale } from 'utils/proxy.util';

export const getContentPage = async (locale: string, publicId: string) => {
    const headers = getDefaultHeaders();
    //fetch is undefined here
    const response = fetch(appendApiRoute(`static-content/v1/${locale}/pages/${publicId}`), {
        method: 'GET',
        headers
    });

    return response;
};

export default async (request: NextApiRequest, response: NextApiResponse) => {
    const currentLocale = getLocale(request);
    const { query } = request;
    const { slug } = query as IQuery;

    const result = await getContentPage(currentLocale, slug);

    return handleProxyResponse(result, response);
};

Failing test:

it('should return handledProxyResponse', async () => {
    const result = await contentProxy(defaultRequest, response);

    expect(result).toEqual(handleProxyResponseReturnValue);
});
tdimoff
  • 353
  • 1
  • 9
  • 2
    Maybe wrong node version? `fetch` is a built-in node function since v. 17.5. In the previous versions, you need to import it. – Nikolay Nov 19 '22 at 15:08
  • Did you add module type to package.json. https://stackoverflow.com/questions/61401475/why-is-type-module-in-package-json-file – Khalil Nov 22 '22 at 19:26

1 Answers1

-6

May be it is a Issue of version. so you can try by use an external module

`npm install node-fetch`

then import it in your code

import fetch from "node-fetch"
  • 2
    as I mentioned above, I do have it installed already. It's build-in Node function since v.17.5. Also gives me "SyntaxError: Cannot use import statement outside a module" and "import http from 'node:http';" – tdimoff Nov 19 '22 at 15:18
  • You need to import it as like this and it will work. const fetch = require('node-fetch') – Yash Kashyap Nov 21 '22 at 09:27
  • Already mentioned OP has node-fetch installed – Sahil Jaidka Apr 19 '23 at 01:45