Create a yotpo-client.ts
under lib directory.
const options = {
method: 'POST',
headers: { accept: 'application/json', 'Content-Type': 'application/json' },
};
export interface YotpoWidget {
method: 'main_widget' | 'bottomline';
result: string;
}
export interface YotpoWidgetJson {
result: { total: number; average_score: number };
}
const APP_KEY = process.env.YOTPO_APP_KEY || '';
const url = `https://staticw2.yotpo.com/batch`;
export const loadYotpoWidgetJS = () => {
const yotpo_script = document.getElementById('yotpo_script');
if (!yotpo_script) {
const e = document.createElement('script');
e.type = 'text/javascript';
e.async = true;
e.id = 'yotpo_script';
e.src = `//staticw2.yotpo.com/${process.env.YOTPO_APP_KEY}/widget.js`;
const t = document.getElementsByTagName('script')[0];
if (t && t.parentNode) t.parentNode.insertBefore(e, t);
}
};
export const getAllReviews = async (productId: number): Promise<YotpoWidget[]> => {
const body = {
methods: [
{
method: 'main_widget',
params: {
pid: productId,
page: 1,
},
},
{
method: 'bottomline',
params: {
pid: productId,
},
},
],
app_key: APP_KEY,
is_mobile: 'false',
};
return (
fetch(url, { ...options, body: JSON.stringify(body) })
.then((res) => res.json())
// eslint-disable-next-line no-console
.catch((e) => console.error(e))
);
};
export const getProductCardReview = async (productIds: number[]): Promise<YotpoWidgetJson[]> => {
const methods = productIds.map((pid) => ({
method: 'bottomline',
params: { pid },
format: 'json',
}));
const body = { methods, app_key: APP_KEY };
return (
fetch(url, { ...options, body: JSON.stringify(body) })
.then((res) => res.json())
// eslint-disable-next-line no-console
.catch((e) => console.error(e))
);
};
Happy Hacking! 🧡