Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

```

const getItems = async (req, res, next) => {


try {
// Pagination :
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const q = req.query.q || "";
let category_ids = req.query.category_ids
let optionFilter
const offset = (page - 1) * limit;

if (q) {
optionFilter = {
where: {
[Op.or]: []
}
};

let filterTitle = {
title: {
[Op.iLike]: `%${q}%`
}
}

let filterKeywords = {
keywords: {
[Op.iLike]: `%${q}%`
}
}

let filterSKU = {
sku: {
[Op.iLike]: `%${q}%`
}
}

optionFilter.where[Op.or].push(filterTitle, filterKeywords, filterSKU)


}

let filterCategory = {
include: {
model: Category
}
}

if (category_ids) {
category_ids = category_ids.map((cat_id) => +cat_id)
filterCategory.include.where = {
id: {
[Op.in]: category_ids
}
}
}

const { count, rows: items } = await Item.findAndCountAll({


...filterCategory,
offset,
limit,
distinct: true,
...optionFilter,
});

const totalPages = Math.ceil(count / limit);

const nextPage = page < totalPages ? page + 1 : null;


const prevPage = page > 1 ? page - 1 : null;

const paginationInfo = {
totalItems: count,
totalPages,
currentPage: page,
nextPage,
prevPage,
items: items,
};

res.status(200).json({ data: paginationInfo })


} catch (error) {
next(error)
}
}
```

You might also like