Skip to content

Commit

Permalink
feat: pass ip information to request on non-cacheable requests (#1384)
Browse files Browse the repository at this point in the history
* feat(client): ability to modify fetchOptions before request

* feat(core): pass ip address for non-cachable requests
  • Loading branch information
chanceaclark authored Sep 18, 2024
1 parent b8f8229 commit 17692ca
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/odd-jokes-love.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bigcommerce/catalyst-core": minor
---

Pass customer ip address into requests that don't rely on cached values.
5 changes: 5 additions & 0 deletions .changeset/twenty-walls-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bigcommerce/catalyst-client": minor
---

Add the ability to hook into the fetchOptions before the request is sent.
11 changes: 9 additions & 2 deletions core/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ const config = {
},
},
customerId: user.id,
fetchOptions: { cache: 'no-store' },
fetchOptions: {
cache: 'no-store',
},
});
} catch (error) {
// eslint-disable-next-line no-console
Expand All @@ -113,7 +115,9 @@ const config = {
},
},
customerId,
fetchOptions: { cache: 'no-store' },
fetchOptions: {
cache: 'no-store',
},
});
} catch (error) {
// eslint-disable-next-line no-console
Expand All @@ -134,6 +138,9 @@ const config = {
const response = await client.fetch({
document: LoginMutation,
variables: { email, password },
fetchOptions: {
cache: 'no-store',
},
});

const result = response.data.login;
Expand Down
14 changes: 14 additions & 0 deletions core/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createClient } from '@bigcommerce/catalyst-client';
import { headers } from 'next/headers';
import { getLocale } from 'next-intl/server';

import { getChannelIdFromLocale } from '~/channels.config';
Expand Down Expand Up @@ -37,4 +38,17 @@ export const client = createClient({
return defaultChannelId;
}
},
beforeRequest: (fetchOptions) => {
if (fetchOptions?.cache && ['no-store', 'no-cache'].includes(fetchOptions.cache)) {
const ipAddress = headers().get('X-Forwarded-For');

if (ipAddress) {
return {
headers: {
'X-Forwarded-For': ipAddress,
},
};
}
}
},
});
20 changes: 15 additions & 5 deletions packages/client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const graphqlApiDomain: string =
export const adminApiHostname: string =
process.env.BIGCOMMERCE_ADMIN_API_HOST ?? 'api.bigcommerce.com';

interface Config {
interface Config<FetcherRequestInit extends RequestInit = RequestInit> {
storeHash: string;
customerImpersonationToken: string;
xAuthToken: string;
Expand All @@ -19,6 +19,7 @@ interface Config {
backendUserAgentExtensions?: string;
logger?: boolean;
getChannelId?: (defaultChannelId: string) => Promise<string> | string;
beforeRequest?: (fetchOptions?: FetcherRequestInit) => Partial<FetcherRequestInit> | undefined;
}

interface BigCommerceResponse<T> {
Expand All @@ -29,8 +30,11 @@ class Client<FetcherRequestInit extends RequestInit = RequestInit> {
private backendUserAgent: string;
private readonly defaultChannelId: string;
private getChannelId: (defaultChannelId: string) => Promise<string> | string;
private beforeRequest?: (
fetchOptions?: FetcherRequestInit,
) => Partial<FetcherRequestInit> | undefined;

constructor(private config: Config) {
constructor(private config: Config<FetcherRequestInit>) {
if (!config.channelId) {
throw new Error('Client configuration must include a channelId.');
}
Expand All @@ -40,6 +44,7 @@ class Client<FetcherRequestInit extends RequestInit = RequestInit> {
this.getChannelId = config.getChannelId
? config.getChannelId
: (defaultChannelId) => defaultChannelId;
this.beforeRequest = config.beforeRequest;
}

// Overload for documents that require variables
Expand Down Expand Up @@ -73,11 +78,13 @@ class Client<FetcherRequestInit extends RequestInit = RequestInit> {
fetchOptions?: FetcherRequestInit;
channelId?: string;
}): Promise<BigCommerceResponse<TResult>> {
const { cache, headers = {}, ...rest } = fetchOptions;
const { headers = {}, ...rest } = fetchOptions;
const query = normalizeQuery(document);
const log = this.requestLogger(query);

const graphqlUrl = await this.getGraphQLEndpoint(channelId);
const { headers: additionalFetchHeaders = {}, ...additionalFetchOptions } =
this.beforeRequest?.(fetchOptions) ?? {};

const response = await fetch(graphqlUrl, {
method: 'POST',
Expand All @@ -86,13 +93,14 @@ class Client<FetcherRequestInit extends RequestInit = RequestInit> {
Authorization: `Bearer ${this.config.customerImpersonationToken}`,
'User-Agent': this.backendUserAgent,
...(customerId && { 'X-Bc-Customer-Id': customerId }),
...additionalFetchHeaders,
...headers,
},
body: JSON.stringify({
query,
...(variables && { variables }),
}),
...(cache && { cache }),
...additionalFetchOptions,
...rest,
});

Expand Down Expand Up @@ -180,6 +188,8 @@ class Client<FetcherRequestInit extends RequestInit = RequestInit> {
}
}

export function createClient<FetcherRequestInit extends RequestInit = RequestInit>(config: Config) {
export function createClient<FetcherRequestInit extends RequestInit = RequestInit>(
config: Config<FetcherRequestInit>,
) {
return new Client<FetcherRequestInit>(config);
}

0 comments on commit 17692ca

Please sign in to comment.