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

Add data fetching example #74

Merged
merged 9 commits into from
Jul 12, 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
22 changes: 22 additions & 0 deletions examples/data-fetching/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = {
parserOptions: {
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
env: {
node: true,
es2021: true,
},
extends: ['eslint:recommended', 'prettier', 'plugin:react/recommended'],
rules: {
'react/react-in-jsx-scope': 'off',
'react/prop-types': 'off',
},
settings: {
react: {
version: '18.1',
},
},
};
3 changes: 3 additions & 0 deletions examples/data-fetching/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
hubspot.config.yml
dist
1 change: 1 addition & 0 deletions examples/data-fetching/.node-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
20.11.0
14 changes: 14 additions & 0 deletions examples/data-fetching/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"overrides": [
{
"files": "*.hubl.html",
"options": {
"parser": "hubl"
}
}
]
}
12 changes: 12 additions & 0 deletions examples/data-fetching/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Copyright 2022 HubSpot, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
4 changes: 4 additions & 0 deletions examples/data-fetching/data-fetching-project/.hsignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
README.md
tsconfig.json
yarn.lock
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module '*.module.css';
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "CMS React - Data fetching",
"outputPath": ""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import pokeCardStyles from '../styles/pokecard.module.css';
import { getTypeColor, PokemonTypes } from '../utils/index.js';

type PokemonData = {
pokemonName: string;
height: number;
weight: number;
profileImage: string;
pokemonType: PokemonTypes;
};

type PokeCardProps = {
pokemonData: PokemonData;
};

export default function PokeCard({ pokemonData }: PokeCardProps) {
const { pokemonName, height, weight, profileImage, pokemonType } =
pokemonData;
const typeColor = getTypeColor(pokemonType);

return (
<div className={pokeCardStyles.wrapper}>
<div
className={pokeCardStyles.card}
style={{ boxShadow: `12px 12px 26px 0px ${typeColor}` }}
>
<div className={pokeCardStyles.profile}>
<img src={profileImage} alt={pokemonName} width="100" height="auto" />
<div className={pokeCardStyles.highlight}></div>
</div>
<h2>{pokemonName}</h2>
<div className={pokeCardStyles.attributes}>
<div className={pokeCardStyles.stack}>
<h4>Height</h4>
<p>{height}m</p>
</div>
<div className={pokeCardStyles.stack}>
<h4>Weight</h4>
<p>{weight}kg</p>
</div>
</div>
</div>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
BooleanField,
ChoiceField,
ModuleFields,
TextField,
} from '@hubspot/cms-components/fields';

export const fields = (
<ModuleFields>
<ChoiceField
name="pokemon"
label="Pokemon"
default={'pikachu'}
choices={[
['bulbasaur', 'Bulbasaur'],
['charizard', 'Charizard'],
['eevee', 'Eevee'],
['mew', 'Mew'],
['mewtwo', 'Mewtwo'],
['pikachu', 'Pikachu'],
['squirtle', 'Squirtle'],
]}
visibility={{
controlling_field_path: 'useCustomFetchUrl',
controlling_value_regex: 'false',
operator: 'EQUAL',
}}
></ChoiceField>
<TextField
name="fetchUrl"
label="Fetch URL"
default="https://swapi.dev/api/people/1/"
visibility={{
controlling_field_path: 'useCustomFetchUrl',
controlling_value_regex: 'true',
operator: 'EQUAL',
}}
/>
<BooleanField
name="useCustomFetchUrl"
label="Use custom fetch URL"
default={false}
/>
<ChoiceField
name="dataFetchingLib"
label="Fetch libraries"
default={'fetch'}
multiple={false}
choices={[
['axios', 'axios'],
['fetch', 'fetch (needs node 18.x)'],
['graphql-request', 'graphql-request'],
['nodeFetchCache', 'nodeFetchCache (fs cache)'],
]}
visibility={{
controlling_field_path: 'useCustomFetchUrl',
controlling_value_regex: 'false',
operator: 'EQUAL',
}}
></ChoiceField>
</ModuleFields>
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import axios from 'axios';
import { request as graphqlRequest, gql } from 'graphql-request';
import { NodeFetchCache, FileSystemCache } from 'node-fetch-cache';
import {
withUrlAndQuery,
logInfo,
ModuleDataFetchResult,
ModulePropsWithoutSSP,
} from '@hubspot/cms-components';
import componentStyles from '../../../styles/component.module.css';
import PokeCard from '../../PokeCard.js';
import {
transformPokemonData,
DataFetchingLibs,
settlePromise,
} from '../../../utils/index.js';

type FieldValues = {
fetchUrl: string;
useCustomFetchUrl: boolean;
pokemon: string;
dataFetchingLib: DataFetchingLibs;
};

type CustomModulePropsWithoutSSP = Omit<
ModulePropsWithoutSSP,
'fieldValues'
> & {
fieldValues: FieldValues | Record<string, any>;
};

const POKEMON_GRAPHQL_SCHEMA_URL = 'https://beta.pokeapi.co/graphql/v1beta/';

const pokemonQuery = gql`
query samplePokeAPIquery($pokemonName: String) {
pokemon_v2_pokemon(where: { name: { _eq: $pokemonName } }) {
name
height
weight
pokemon_v2_pokemonsprites {
sprites
}
pokemon_v2_pokemontypes {
pokemon_v2_type {
name
}
}
}
}
`;

// Using node-fetch-catch can optimize your data fetching by caching data locally within the
// Lambda function's file system which will help improve performance and reduce latency.
const nodeFetchCache = NodeFetchCache.create({
cache: new FileSystemCache({
cacheDirectory: '/tmp/nodeFetchCache',
ttl: 1000 * 60 * 5, // 5 mins
}),
});

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') {
return graphqlRequest(POKEMON_GRAPHQL_SCHEMA_URL, pokemonQuery, {
pokemonName: fieldValues.pokemon,
}).then((value: any) => {
return {
json: value,
duration: Date.now() - start,
};
});
}

if (dataFetchingLib === 'nodeFetchCache') {
return nodeFetchCache(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}`,
);
}

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}`,
);
}

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

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

logInfo('before data fetch');
const dataPromise = getDataPromise(fieldValues) as Promise<{
json: JSON;
duration: number;
}>;

const results = await settlePromise(dataPromise);
logInfo('after data fetch');

return {
serverSideProps: { results, urlSearchParams: url.search },
caching: {
cacheControl: {
maxAge: 60,
},
},
};
},
);

export function Component({
fieldValues,
serverSideProps = { results: {}, urlSearchParams: '' },
}: {
fieldValues: FieldValues;
serverSideProps: {
results: Record<string, any>;
urlSearchParams: string;
};
}) {
const { results } = serverSideProps;
const { json, duration } = results.value;
const { useCustomFetchUrl, dataFetchingLib, fetchUrl } = fieldValues;
const lib = useCustomFetchUrl ? 'fetch' : dataFetchingLib;

return (
<div className={componentStyles.summary}>
<h2>
Fetched data from <code>{urlToFetch(fieldValues)}</code> via {lib} in{' '}
{duration}ms
</h2>
{useCustomFetchUrl ? (
<details>
<summary>
<h3 style={{ display: 'inline', cursor: 'pointer' }}>
...via {fetchUrl} <small>(duration = {duration}ms)</small>
</h3>
</summary>
<br />
<code>
<pre>{JSON.stringify(results.value, null, 2)}</pre>
</code>
</details>
) : (
json && (
<PokeCard
pokemonData={transformPokemonData(json, dataFetchingLib)}
key={dataFetchingLib}
/>
)
)}
</div>
);
}

function urlToFetch(fieldValues: FieldValues) {
if (fieldValues.useCustomFetchUrl) {
return fieldValues.fetchUrl;
}

return `https://pokeapi.co/api/v2/pokemon/${fieldValues.pokemon}`;
}

export const meta = {
label: 'Fetcher',
};

// @ts-ignore-next-line
export { fields } from './fields.tsx';
Loading
Loading