Using Node.js with Sequelize:
Imagine we have a scenario where we need to filter and retrieve records from a PostgreSQL database using Sequelize ORM. We'll create a function to filter repair records based on various criteria such as category, partName, isPart, granteeCode, province, startDate, and endDate.
Explanation:
Sequelize Setup:
The function uses Sequelize ORM to interact with a PostgreSQL database.
The Repair, Guaranti, and Category models are imported.
Authentication Check:
The function checks if the user token is valid and of the correct type.
Extracting Filters:
The function extracts various filters (category, partName, isPart, granteeCode, province, startDate, endDate) from the args.where object.
Constructing the Query:
A where object is constructed to hold the query conditions.
The conditions are dynamically added based on the presence of filter values.
The deleteUndefinedsFromObject utility removes any undefined properties from the where object.
Grantee Data Lookup:
If granteeCode or province are provided, the function queries the Guaranti model to find the corresponding grantee data.
The granteeId is added to the where condition if a matching grantee is found.
Part Name Condition:
The partName and isPart conditions are added to the where object.
Querying Repairs:
The Repair model is queried using findAndCountAll with the constructed where conditions.
The results include related grantee and category details using the include option.
Pagination is handled using limit and offset.
Returning Results:
The function returns an object containing the total count of matching records and the list of items.