Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
jontallboy committed May 31, 2024
1 parent 7da4c42 commit 5e4bcc2
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 105 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const fields = (
<ChoiceField
name="dataFetchingLib"
label="Fetch libraries"
default={'graphql-request'}
default={'fetch'}
multiple={false}
choices={[
['axios', 'axios'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { NodeFetchCache, FileSystemCache } from 'node-fetch-cache';
import {
withUrlAndQuery,
logInfo,
logError,
ModuleDataFetchResult,
ModulePropsWithoutSSP,
} from '@hubspot/cms-components';
Expand All @@ -13,10 +12,9 @@ import PokeCard from '../../PokeCard.js';
import {
transformPokemonData,
DataFetchingLibs,
settlePromise,
} from '../../../utils/index.js';

const FALLBACK_FETCH_LIBRARY = 'axios';

type FieldValues = {
fetchUrl: string;
useCustomFetchUrl: boolean;
Expand Down Expand Up @@ -60,111 +58,88 @@ const nodeFetchCache = NodeFetchCache.create({
}),
});

export const getServerSideProps = withUrlAndQuery(
async (
moduleProps: CustomModulePropsWithoutSSP,
extraDeps,
): Promise<ModuleDataFetchResult> => {
const fieldValues = moduleProps.fieldValues as FieldValues;
const { url } = extraDeps;

const dataPromises = [];
const start = Date.now();

const dataFetchingLib: string = fieldValues.dataFetchingLib;
const fetchUrl = urlToFetch(fieldValues);

if (dataFetchingLib && !fieldValues.useCustomFetchUrl) {
if (dataFetchingLib === 'axios') {
dataPromises.push(
axios.get(fetchUrl).then((response: any) => {
return {
json: response.data,
duration: Date.now() - start,
};
}),
);
}
export function getDataPromise(fieldValues: FieldValues) {
const { dataFetchingLib, useCustomFetchUrl } = fieldValues;
const fetchUrl = urlToFetch(fieldValues);
const start = Date.now();

if (dataFetchingLib && !useCustomFetchUrl) {
if (dataFetchingLib === 'axios') {
return axios.get(fetchUrl).then((response: any) => {
return {
json: response.data,
duration: Date.now() - start,
};
});
}

if (dataFetchingLib === 'graphql-request') {
dataPromises.push(
graphqlRequest(POKEMON_GRAPHQL_SCHEMA_URL, pokemonQuery, {
pokemonName: fieldValues.pokemon,
}).then((value: any) => {
return {
json: value,
duration: Date.now() - start,
};
}),
);
}
if (dataFetchingLib === 'graphql-request') {
return graphqlRequest(POKEMON_GRAPHQL_SCHEMA_URL, pokemonQuery, {
pokemonName: fieldValues.pokemon,
}).then((value: any) => {
return {
json: value,
duration: Date.now() - start,
};
});
}

if (dataFetchingLib === 'fetch') {
if (!fetch) {
throw new Error(
`Fetch API is not defined, node version = ${process.versions.node}`,
);
}
if (dataFetchingLib === 'nodeFetchCache') {
return nodeFetchCache(fetchUrl).then(async (response) => {
return {
json: await response.json(),
duration: Date.now() - start,
};
});
}

dataPromises.push(
fetch(fetchUrl).then(async (response) => {
return {
json: await response.json(),
duration: Date.now() - start,
};
}),
if (dataFetchingLib === 'fetch') {
logInfo('here');
if (!fetch) {
throw new Error(
`Fetch API is not defined, node version = ${process.versions.node}`,
);
}

if (dataFetchingLib === 'nodeFetchCache') {
dataPromises.push(
nodeFetchCache(fetchUrl).then(async (response) => {
return {
json: await response.json(),
duration: Date.now() - start,
};
}),
);
}
} else {
dataPromises.push(
axios.get(fetchUrl).then((response: any) => {
return {
json: response.data,
duration: Date.now() - start,
};
}),
return fetch(fetchUrl).then(async (response) => {
return {
json: await response.json(),
duration: Date.now() - start,
};
});
}
} else {
if (!fetch) {
throw new Error(
`Fetch API is not defined, node version = ${process.versions.node}`,
);
}

logInfo('before data fetch');
return fetch(fetchUrl).then(async (response) => {
return {
json: await response.json(),
duration: Date.now() - start,
};
});
}
}

const jsonData = (await Promise.allSettled(dataPromises)).map(
(result: any) => {
if (result.status === 'fulfilled') {
logInfo(
'Fetch success',
Object.keys(result.value.json).join(', '),
`duration = ${result.value.duration}`,
);
} else {
logError('Fetch failure');
}
export const getServerSideProps = withUrlAndQuery(
async (
moduleProps: CustomModulePropsWithoutSSP,
extraDeps,
): Promise<ModuleDataFetchResult> => {
const fieldValues = moduleProps.fieldValues as FieldValues;
const { url } = extraDeps;

return result.status === 'fulfilled'
? result.value
: {
status: result.status,
reason: result.reason,
};
},
);
logInfo('after data fetch');
logInfo('before data fetch');
const dataPromise = getDataPromise(fieldValues) as Promise<{
json: JSON;
duration: number;
}>;

const results =
dataFetchingLib && !fieldValues.useCustomFetchUrl
? [dataFetchingLib, jsonData[0]]
: jsonData[0];
const results = await settlePromise(dataPromise);
logInfo('after data fetch');

return {
serverSideProps: { results, urlSearchParams: url.search },
Expand All @@ -188,10 +163,9 @@ export function Component({
};
}) {
const { results } = serverSideProps;
const { useCustomFetchUrl, dataFetchingLib } = fieldValues;
const responseData = useCustomFetchUrl ? results : results[1];
const { json, duration } = responseData;
const lib = useCustomFetchUrl ? FALLBACK_FETCH_LIBRARY : dataFetchingLib;
const { json, duration } = results.value;
const { useCustomFetchUrl, dataFetchingLib, fetchUrl } = fieldValues;
const lib = useCustomFetchUrl ? 'fetch' : dataFetchingLib;

return (
<div className={componentStyles.summary}>
Expand All @@ -203,17 +177,16 @@ export function Component({
<details>
<summary>
<h3 style={{ display: 'inline', cursor: 'pointer' }}>
...via {fieldValues.fetchUrl}{' '}
<small>(duration = {results.duration}ms)</small>
...via {fetchUrl} <small>(duration = {duration}ms)</small>
</h3>
</summary>
<br />
<code>
<pre>{JSON.stringify(results.json, null, 2)}</pre>
<pre>{JSON.stringify(results.value, null, 2)}</pre>
</code>
</details>
) : (
results && (
json && (
<PokeCard
pokemonData={transformPokemonData(json, dataFetchingLib)}
key={dataFetchingLib}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { logError, logInfo } from '@hubspot/cms-components';

export type DataFetchingLibs = 'graphql-request' | 'axios';

export function transformPokemonData(
Expand Down Expand Up @@ -68,3 +70,14 @@ export function getTypeColor(pokemonType: PokemonTypes) {
return 'green';
}
}

export async function settlePromise(
promise: Promise<{ json: JSON; duration: number }>,
) {
return promise
.then((value: { json: JSON; duration: number }) => {
logInfo({ status: 'fulfilled' });
return { status: 'fulfilled', value };
})
.catch((reason) => logError({ status: 'rejected', reason }));
}

0 comments on commit 5e4bcc2

Please sign in to comment.