Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/apiKey in fetcher #163

Merged
merged 4 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/helpers/fetchers/axios.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import type { FetcherFunction } from '../../types';
import type { ExtraFetchParams, FetcherFunction } from '../../types';
import type { AxiosStatic } from 'axios';
import { FetcherError } from '../misc';

export type AxiosRequirement = Pick<AxiosStatic, 'request' | 'isAxiosError'>;

export const constructFetcher =
(axios: AxiosRequirement): FetcherFunction =>
(axios: AxiosRequirement, extra?: ExtraFetchParams): FetcherFunction =>
async (params) => {
try {
const { data } = await axios.request(params);
// adding apiKey to headers if it's provided
const headers = extra?.apiKey
? { 'X-API-KEY': extra.apiKey, ...params.headers }
: params.headers;
const { data } = await axios.request({ ...params, headers });

return data;
} catch (error: any) {
Expand Down
18 changes: 15 additions & 3 deletions src/helpers/fetchers/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
import type { FetcherFunction } from '../../types';
import type { ExtraFetchParams, FetcherFunction } from '../../types';
import { FetcherError } from '../misc';

// @TODO may not work with node-fetch
type Fetch = typeof fetch;

export const constructFetcher =
(fetch: Fetch): FetcherFunction =>
(fetch: Fetch, extra?: ExtraFetchParams): FetcherFunction =>
async (params) => {
try {
const { url, method, signal } = params;
const body = method === 'POST' ? JSON.stringify(params.data) : null;
const headers =
// Only JSON response for POST requests
const POSTheaders =
method === 'POST' && body
? {
'Content-Type': 'application/json',
}
: undefined;

// adding apiKey to headers if it's provided
const apiHeaders = extra?.apiKey
? { 'X-API-KEY': extra.apiKey, ...params.headers }
: undefined;

// all headers combined
const headers =
POSTheaders || apiHeaders || params.headers
? { ...apiHeaders, ...POSTheaders, ...params.headers }
: undefined;

const response = await fetch(url, { method, body, signal, headers });

const data = await response.json();
Expand Down
8 changes: 5 additions & 3 deletions src/legacy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ type TxResponse = Web3UnpromiEvent | ContractTransaction;
type LegacyOptions = {
chainId?: number;
apiURL?: string;
apiKey?: string;
web3Provider?: Web3;
ethersDeps?: EthersProviderDeps; // need to be a provider with signer for approve requests
account?: Address;
Expand All @@ -71,6 +72,7 @@ export class ParaSwap {
constructor({
chainId = 1,
apiURL = API_URL,
apiKey,
web3Provider,
ethersDeps,
account,
Expand All @@ -84,17 +86,17 @@ export class ParaSwap {
this.account = account;

const fetcher = axios
? constructAxiosFetcher(axios)
? constructAxiosFetcher(axios, { apiKey })
: fetch
? constructFetchFetcher(fetch)
? constructFetchFetcher(fetch, { apiKey })
: null;

assert(fetcher, 'at least one fetcher is needed');
this.fetcher = fetcher;

if (!web3Provider && !ethersDeps) {
this.sdk = constructPartialSDK(
{ fetcher, apiURL, chainId },
{ fetcher, apiURL, apiKey, chainId },
constructGetBalances,
constructGetTokens,
constructGetSpender,
Expand Down
20 changes: 15 additions & 5 deletions src/sdk/simple.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import type {
TxHash,
Address,
FetcherFunction,
ExtraFetchParams,
} from '../types';

import type { EthersProviderDeps } from '../helpers';
Expand Down Expand Up @@ -123,12 +124,14 @@ export type SimpleSDK = {
nftOrders: NFTOrderHandlers<TxHash>;
};

export type FetcherOptions =
export type FetcherOptions = (
| {
axios: AxiosRequirement;
}
| { fetch: typeof fetch }
| { fetcher: FetcherFunction };
| { fetcher: FetcherFunction }
) &
ExtraFetchParams;

type SimpleOptions = ConstructBaseInput & FetcherOptions;

Expand All @@ -138,12 +141,19 @@ export type ProviderOptions = (EthersProviderDeps | { web3: Web3 }) & {

const constructFetcher = (options: FetcherOptions): FetcherFunction => {
if ('axios' in options) {
return constructAxiosFetcher(options.axios);
return constructAxiosFetcher(options.axios, options);
}
if ('fetch' in options) {
return constructFetchFetcher(options.fetch);
return constructFetchFetcher(options.fetch, options);
}
return options.fetcher;
return (params) => {
// adding apiKey to headers if it's provided
const headers = options?.apiKey
? { 'X-API-KEY': options.apiKey, ...params.headers }
: params.headers;

return options.fetcher({ ...params, headers });
};
};

/** @description construct SDK with methods that fetch from API and optionally with blockchain provider calling methods */
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ export type FetcherFunction = <T, URL extends string = string>(
params: FetcherGetInput<URL> | FetcherPostInput<URL>
) => Promise<T>;

// authentication or some other params required in `fetcher`
export type ExtraFetchParams = { apiKey?: string };

export interface ConstructFetchInput extends ConstructBaseInput {
fetcher: FetcherFunction;
}
Expand Down
Loading