Files
explore/nextjs/utils/fetchProxy.ts
T
tom goriunovandGitHub 9babbc4b2f Enhance OG tags with API data (#1806)
* simple fetch data for token instance page

* generate enhanced metadata

* group query params in page props

* make base gSSP function generic

* add metric for search engine bots

* measure api request duration

* get API data for token, address and dapp pages

* improve typings for apiData prop

* add ENV variable

* tweak logs for /media-type requests

* [skip ci] add prefix to default metrics
2024-04-16 10:27:47 +02:00

58 lines
1.5 KiB
TypeScript

import type { IncomingMessage } from 'http';
import _pick from 'lodash/pick';
import type { NextApiRequest } from 'next';
import type { NextApiRequestCookies } from 'next/dist/server/api-utils';
import type { RequestInit, Response } from 'node-fetch';
import nodeFetch from 'node-fetch';
import { httpLogger } from 'nextjs/utils/logger';
import * as cookies from 'lib/cookies';
export default function fetchFactory(
_req: NextApiRequest | (IncomingMessage & { cookies: NextApiRequestCookies }),
) {
// first arg can be only a string
// FIXME migrate to RequestInfo later if needed
return function fetch(url: string, init?: RequestInit): Promise<Response> {
const apiToken = _req.cookies[cookies.NAMES.API_TOKEN];
const headers = {
accept: _req.headers['accept'] || 'application/json',
'content-type': _req.headers['content-type'] || 'application/json',
cookie: apiToken ? `${ cookies.NAMES.API_TOKEN }=${ apiToken }` : '',
..._pick(_req.headers, [
'x-csrf-token',
'Authorization',
// feature flags
'updated-gas-oracle',
]) as Record<string, string | undefined>,
};
httpLogger.logger.info({
message: 'API fetch via Next.js proxy',
url,
// headers,
});
const body = (() => {
const _body = init?.body;
if (!_body) {
return;
}
if (typeof _body === 'string') {
return _body;
}
return JSON.stringify(_body);
})();
return nodeFetch(url, {
...init,
headers,
body,
});
};
}