Nextjs cached fetching server-side
Unanswered
Masai Lion posted this in #help-forum
Masai LionOP
Is this the best way to fetch data using paramaters along with caching ?
export const getEntities = async (
params: Params
): Promise<EntityResponse | any> => {
'use server';
unstable_noStore();
return await cache(
async () => {
const fetchEntities = async (params: Params) => {
const page = Number(params.page) || 1;
const pageLimit = Number(params.limit) || 10;
const name = params.search || null;
const offset = (page - 1) * pageLimit;
const whereClause = name
? { name: { contains: name, mode: 'insensitive' } }
: ({} as any);
const [entities, totalEntities] = await Promise.all([
prisma.entity.findMany({
skip: offset,
take: pageLimit,
where: whereClause
}),
prisma.entity.count({
where: whereClause
})
]);
const pageCount = Math.ceil(totalEntities / pageLimit);
const metadata = {
total: totalEntities,
pageCount,
currentPage: page,
perPage: pageLimit
};
return { entities, metadata };
};
try {
const { entities, metadata } = await fetchEntities(params);
return { data: entities, metadata };
} catch (error) {
return { data: [], metadata: {} };
}
},
[TAG, JSON.stringify(params)],
{
revalidate: 20,
tags: [TAG, JSON.stringify(params)]
}
)();
};