Skip to content

Commit

Permalink
feat: add pagination for category property api
Browse files Browse the repository at this point in the history
  • Loading branch information
Behzad-rabiei committed Sep 12, 2024
1 parent 7066d3f commit 14c6e5b
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions src/services/discourse/category.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,34 @@ async function getCategoriesByEndPoint(filters: any, options: any): Promise<any>
limit = limit && parseInt(limit, 10) > 0 ? parseInt(limit, 10) : 10;
page = page && parseInt(page, 10) > 0 ? parseInt(page, 10) : 1;
skip = (page - 1) * limit;
const totalQuery = `
MATCH (forum:DiscourseForum {endpoint: "${endPoint}"})
MATCH (dc:DiscourseCategory {forumUuid: forum.uuid})
${name ? `WHERE dc.name =~ '(?i).*${name}.*'` : ''}
RETURN COUNT(dc) as totalResults
`;
const query = `
MATCH (forum:DiscourseForum {endpoint: "${endPoint}"})
MATCH (dc:DiscourseCategory {forumUuid: forum.uuid})
${name ? `WHERE dc.name =~ '(?i).*${name}.*'` : ''}
RETURN dc.id as categoryId, dc.name as name, dc.color as color, dc.descriptionText as description
ORDER BY ${sortBy ? sortBy : 'dc.id'}
SKIP ${skip}
LIMIT ${limit}
`;
MATCH (forum:DiscourseForum {endpoint: "${endPoint}"})
MATCH (dc:DiscourseCategory {forumUuid: forum.uuid})
${name ? `WHERE dc.name =~ '(?i).*${name}.*'` : ''}
RETURN dc.id as categoryId, dc.name as name, dc.color as color, dc.descriptionText as description
ORDER BY ${sortBy ? sortBy : 'dc.id'}
SKIP ${skip}
LIMIT ${limit}
`;

try {
const totalResultDataNeo4j = await Neo4j.read(totalQuery);
const { records: totalResultData } = totalResultDataNeo4j;
// @ts-ignore
const { _fieldLookup, _fields } = totalResultData[0];
const totalResults = _fields[_fieldLookup['totalResults']] as number;

// Fetch paginated category results
const neo4jCategories = await Neo4j.read(query);
const { records: categories } = neo4jCategories;

// Map the results to an object array
const CategoryList = categories.map((category) => {
// @ts-ignore
const { _fieldLookup, _fields } = category;
Expand All @@ -38,7 +54,18 @@ async function getCategoriesByEndPoint(filters: any, options: any): Promise<any>
const description = _fields[_fieldLookup['description']] as string;
return { categoryId, name, color, description };
});
return CategoryList;

// Calculate total pages
const totalPages = Math.ceil(totalResults / limit);

// Return structured response
return {
results: CategoryList,
page,
limit,
totalPages,
totalResults,
};
} catch (error) {
logger.error(error, 'Failed to get category list by endpoint');
throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Failed to get category list by endpoint');
Expand Down

0 comments on commit 14c6e5b

Please sign in to comment.