Skip to content

Commit

Permalink
feat: fetch hook
Browse files Browse the repository at this point in the history
  • Loading branch information
nicholasio committed Sep 25, 2023
1 parent 466d27b commit 846338c
Show file tree
Hide file tree
Showing 6 changed files with 116 additions and 7 deletions.
30 changes: 24 additions & 6 deletions packages/core/src/data/api/fetch-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LOGTYPE, addQueryArgs, getHeadlessConfig, log } from '../../utils';
import { LOGTYPE, addQueryArgs, getHeadstartWPConfig, log } from '../../utils';

export const getAuthHeader = () => {
return null;
Expand All @@ -15,15 +15,26 @@ export const getAuthHeader = () => {
* @returns {object}
*/
export const apiPost = async (url: string, args: { [index: string]: any } = {}) => {
const response = await fetch(url, {
const config = getHeadstartWPConfig();

const fetchArgs = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(args),
});
};

const { url: filteredUrl, args: filteredArgs } = config.filters?.fetch?.(
'POST',
url,
fetchArgs,
) ?? {
url,
fetchArgs,
};

const config = getHeadlessConfig();
const response = await fetch(filteredUrl, filteredArgs);

if (config.debug?.requests) {
log(LOGTYPE.DEBUG, 'POST', url, args);
Expand Down Expand Up @@ -60,15 +71,22 @@ export const apiGet = async (
}
: {};

const config = getHeadlessConfig();
const config = getHeadstartWPConfig();

const fetchUrl = addQueryArgs(url, queryArgs);

if (config.debug?.requests) {
log(LOGTYPE.DEBUG, 'GET', fetchUrl, args);
}

const data = await fetch(fetchUrl, args);
const { url: filteredUrl, args: filteredArgs } = config.filters?.fetch?.(
'GET',
fetchUrl,
args,
burstCache,
) ?? { url: fetchUrl, args };

const data = await fetch(filteredUrl, filteredArgs);

const receivedHeaders: { [index: string]: any } = [
...Array.from(data.headers.entries()),
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,15 @@ export type HeadlessConfig = {
redirects?: boolean;
devMode?: boolean;
};
filters?: {
fetch?: (
method: 'POST' | 'GET',
url: string,
args: Record<string, any>,
burstCache?: boolean,
) => {
url: string;
args: Record<string, any>;
};
};
};
2 changes: 2 additions & 0 deletions packages/core/src/utils/getHeadlessConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export function getHeadstartWPConfig() {
hostUrl,
integrations,
debug,
filters,
} = __10up__HEADLESS_CONFIG;

const headlessConfig: HeadlessConfig = {
Expand All @@ -41,6 +42,7 @@ export function getHeadstartWPConfig() {
useWordPressPlugin: useWordPressPlugin || false,
integrations,
debug,
filters,
sites: (sites || []).map((site) => {
// if host is not defined but hostUrl is, infer host from hostUrl
if (typeof site.host === 'undefined' && typeof site.hostUrl !== 'undefined') {
Expand Down
42 changes: 42 additions & 0 deletions packages/next/src/config/__tests__/withHeadlessConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { toStringWithFunctions } from '../withHeadlessConfig';

describe('toStringWithFunctions', () => {
it('converts regular objects to strings', () => {
const obj = {
a: 'a',
b: 'b',
c: 'c',
};
expect(toStringWithFunctions(obj)).toMatchInlineSnapshot(`
"{
"a": "a",
"b": "b",
"c": "c"
}"
`);
});
it('converts functions to strings', () => {
const obj = {
a: 'test',
fn: () => {
// eslint-disable-next-line no-console
console.log('test');
},
nested: {
fn: () => {},
},
};
expect(toStringWithFunctions(obj)).toMatchInlineSnapshot(`
"{
"a": "test",
"fn": () => {
// eslint-disable-next-line no-console
console.log('test');
},
"nested": {
"fn": () => { }
}
}"
`);
});
});
30 changes: 29 additions & 1 deletion packages/next/src/config/withHeadlessConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,34 @@ const isPackageInstalled = (packageName: string): boolean => {

return false;
};

/**
* Stringify an object, including functions
*
* @param obj A JavaScript object
*
* @returns
*/
export function toStringWithFunctions(obj: Record<string, any>) {
const placeholder = '____HEADSTARTWP_FUNCTION_PLACEHOLDER____';
const fns: Array<any> = [];
let json = JSON.stringify(
obj,
function (key, value) {
if (typeof value === 'function') {
fns.push(value);
return placeholder;
}
return value;
},
2,
);
json = json.replace(new RegExp(`"${placeholder}"`, 'g'), function () {
return fns.shift();
});
return json;
}

function traverse(rules) {
for (const rule of rules) {
if (typeof rule.loader === 'string' && rule.loader.includes('css-loader')) {
Expand Down Expand Up @@ -155,7 +183,7 @@ export function withHeadlessConfig(
webpack: (config, options) => {
const importSetHeadlessConfig = `
import { setHeadstartWPConfig } from '@headstartwp/core/utils';
setHeadstartWPConfig(${JSON.stringify(headlessConfig)});
setHeadstartWPConfig(${toStringWithFunctions(headlessConfig)});
`;

// clear webpack cache whenever headless.config.js changes or one of the env files
Expand Down
8 changes: 8 additions & 0 deletions projects/wp-nextjs/headless.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,12 @@ module.exports = {
*/
devMode: process.env?.ENABLE_DEV_MODE === 'true',
},
filters: {
fetch: (method, url, args) => {
return {
url,
args,
};
},
},
};

0 comments on commit 846338c

Please sign in to comment.