How to create Pagination with vue-table2? - pagination

I'm using the Vue-table2 for rendering the table. https://github.com/ratiw/vuetable-2
<vuetable ref="vuetable"
:api-url= "apiurl"
:fields="fields">
</vuetable>
My Server Api Response doesn't have any Pagination response in it . The data returned by server is
{
"data":[
{
"id":22535,
"message":"Message1",
"message_type":"tag1",
"time":"2018-08-13T14:41:57Z",
"username":"rahuln"
},
{
"id":22534,
"message":"Message2",
"message_type":"tag2",
"time":"2018-08-13T14:02:27Z",
"username":"govindp"
},
..................
],
"error":null,
"success":true
}
This is the first time I'm Using Vue-js. How can i add the pagination into it and still using vue-table2.
Thanks In advance.

Since you don't have pagination values you must insert it we gonna trick vue-table like this
<template>
<div>
<vuetable ref="vuetable" api-url="/api/ahmed" :fields="fields" pagination-path="" #vuetable:pagination-data="onPaginationData" #vuetable:load-success="loadSuccess">
</vuetable>
<vuetable-pagination ref="pagination" #vuetable-pagination:change-page="onChangePage"></vuetable-pagination>
</div>
</template>
<script>
import Vuetable from 'vuetable-2/src/components/Vuetable'
import VuetablePagination from 'vuetable-2/src/components/VuetablePagination'
export default {
components: {
Vuetable,
VuetablePagination,
},
data() {
return {
fields: ['name', 'email', 'birthdate', 'nickname', 'gender', '__slot:actions'],
allData: false,
currentPage: 1,
}
},
mounted() {
},
methods: {
onPaginationData(paginationData) {
this.$refs.pagination.setPaginationData(paginationData)
},
loadSuccess(data) {
this.$refs.vuetable.$nextTick(()=>{
if (!this.allData) {
this.allData = data;
}
if (!data.data.per_page) {
data = this.setData(this.currentPage);
this.$refs.vuetable.loadSuccess(data);
}
})
},
setData(Page) {
var data = JSON.parse(JSON.stringify(this.allData));
var total = data.data.data.length;
var perPage = 10;
var currentPage = Page;
var lastPage = parseInt(total / perPage) + ((total % perPage) === 0 ? 0 : 1)
var from = parseInt((currentPage - 1) * perPage) + 1;
var to = from + perPage - 1;
to = to > total ? total : to;
console.log(from,to)
var newData = this.allData.data.data.filter(function(element, index) {
if (index >= from-1 && index <= to-1) {
console.log(index,from,to)
return true;
}
return false;
})
// console.log(newData)
// return newData;
data.data = {
"total": total,
"per_page": perPage,
"current_page": currentPage,
"last_page": lastPage,
"next_page_url": "",
"prev_page_url": null,
"from": from,
"to": to,
data: newData
}
// console.log(data)
this.currentPage = Page;
this.$refs.vuetable.loadSuccess(data);
return data;
},
onChangePage(page) {
this.setData(page);
}
}
}
</script>

Related

API getting called multiple times

When testing the API I have noticed that it is getting called around 6 times, there is no for/foreach loop that would make it run several times in the code so am unsure as to why this may be happening.
The API runs every time a user goes onto the Landing Screen.
Any advice would be appreciated
exports.getFilteredOpportunities = async (req, res) => {
let mongoQuery = generateMongoQuery(req);
try {
const opps = await Opportunity.find(mongoQuery)
.select(removeItems)
.sort({
createdAt: -1
});
res.status(200).json({
opportunities: opps,
});
} catch (error) {
res.status(500).json({
status: "error",
message: error,
});
}
};
GenerateMongoQuery function
const generateMongoQuery = (req) => {
let query = {};
// search param used searching through Title field, ie. search=food
if (req.query.search && req.query.search.length > 0) {
query.$or = [{}, {}];
query.$or[0].Title = query.$or[1].Description = new RegExp(
`${req.query.search}`,
"i"
);
}
// location param, i.e location=Glasgow,Manchester
if (req.query.location && req.query.location.length > 0) {
query.location = {
$in: req.query.location.split(",")
};
}
// timeslot param, i.e timeslot=Evening,Morning
if (req.query.timeslot && req.query.timeslot.length > 0) {
query.timeslot = {
$in: req.query.timeslot.split(",")
};
}
// category param, returning corresponding id i.e category=
if (req.query.category && req.query.category.length > 0) {
query.category = {
$in: req.query.category.split(",")
};
}
// Dont load expired opportunities
query.eventDate = {
$gte: new Date().toDateString()
};
// Only return non-cancelled opportunities
query.isCancelled = false;
return query;
};
The landing Screen
import { useState, useEffect } from "react";
import Opportunities from "../components/molecules/Opportunities";
import Filters from "../components/organisms/Filters";
import { IOpportunity } from "../Models/IOpportunity";
import OpportunitiesClient from "../Api/opportunitiesClient";
import Utils from "../Utils/Utils";
import FiltersClient from "../Api/filtersClient";
import { IFilters } from "../Models/IFilters";
import { ISelectedFilters } from "../Models/ISelectedFilters";
import Header from "../components/atoms/Header";
import Footer from "../components/atoms/Footer";
export default function LandingScreen(props) {
const [opportunities, setOpportunities] = useState<IOpportunity[]>([]);
const [filters, setFilters] = useState<IFilters[]>([]);
const [checkedFilters, setCheckedFilters] = useState<
ISelectedFilters | undefined
>({
Location: [],
Category: [],
Timeslot: [],
});
const [isLoading, setLoading] = useState<boolean>(true);
const [allResultsLoaded, setAllResultsLoaded] = useState<boolean>(false);
let pageToGet = 1;
const [scrollPosition, setScrollPosition] = useState(0);
const [totalOpps, setTotalOpps] = useState(0);
useEffect(() => {
getOpportunities();
getFilters();
}, []);
useEffect(() => {
setTotalOpps(opportunities.length);
}, [opportunities]);
const handleScroll = () => {
setScrollPosition(window.pageYOffset);
let scrollHeight = 0;
if ((props.scrollHeight === null) !== undefined) {
scrollHeight = +props.scrollHeight;
} else {
scrollHeight = document.scrollingElement.scrollHeight;
}
if (
window.innerHeight + document.documentElement.scrollTop >=
scrollHeight
) {
if (allResultsLoaded === false) {
setLoading(true);
}
setTimeout(() => {
pageToGet += 1;
getOpportunities();
}, 600);
}
window.removeEventListener("scroll", handleScroll);
};
window.addEventListener("scroll", handleScroll, { passive: true });
const setItemChecked = (filtername: string, filterType: string) => {
// reset page and results
pageToGet = 1;
setAllResultsLoaded(false);
setCheckedFilters(
Utils.setItemChecked(filtername, filterType, checkedFilters)
);
};
const resetFilters = () => {
// reset page and results
pageToGet = 1;
setAllResultsLoaded(false);
checkedFilters.Location = [];
checkedFilters.Category = [];
checkedFilters.Timeslot = [];
getOpportunities();
};
const getFilters = () => {
FiltersClient.getAll().then((filters) => {
setFilters(filters);
});
};
const getOpportunities = () => {
console.log(opportunities);
OpportunitiesClient.getWithParams(
Utils.getAxiosParams(checkedFilters)
).then((res) => {
definePage(res);
if (opportunities.length === res["opportunities"].length)
setAllResultsLoaded(true);
setLoading(false);
});
};
const definePage = (res) => {
if (pageToGet === 1) {
setOpportunities(res["opportunities"].slice(0, 15));
} else {
setOpportunities(
opportunities.concat(
res["opportunities"].slice(
opportunities.length,
opportunities.length + 15
)
)
);
}
};
return (
<div>
<Header page="landing" includePostButton={true} />
<div
data-testid="test-div1"
className="grid md:grid-cols-[150px_auto] sm:grid-cols-1 md:grid-flow-col gap-4 mx-4 mb-5 my-10"
>
<div></div>
<div className="card-container-title">
{totalOpps} Results{" "}
{checkedFilters.Location.length > 0 ? "(Filtered)" : ""}
</div>
</div>
<div
data-testid="test-div3"
className="grid md:grid-cols-[150px_auto] sm:grid-cols-1 md:grid-flow-col gap-4 mx-4"
>
<div>
<Filters
filters={filters}
getChecked={setItemChecked}
urlCall={getOpportunities}
resetFilters={resetFilters}
checkedFilters={checkedFilters}
/>
</div>
<div
data-testid="test-div4"
className={isLoading ? "opacity-50" : ""}
>
<div className="col-span-2">
<Opportunities
items={opportunities}
isLoading={isLoading}
allResultsLoaded={allResultsLoaded}
/>
</div>
</div>
</div>
<Footer />
</div>
);
}

How to make pagination with NodeJS?

i have a controller and i want to make pagination with 5 records per page. How can i do it with Nodejs i really need help.
const getPagination = (page, size) => {
const limit = size ? +size : 5; // Fetch 5 records
const offset = page ? page * limit : 0;// Start from page 0
return { limit, offset };
};
// Find all car with condition and how can i add pagination ?
export function findAllCar( req, res){
const name = req.query.name;
const color = req.query.color;
const brand = req.query.brand;
var condition = name ? {
name: { [Op.iLike]: `%${name}%` },
color: { [Op.iLike]: `%${color}%` },
brand: { [Op.iLike]: `%${brand}%` },
} : null;
Car.findAll({ where: condition })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving CARS."
});
});
}
you need to add limit and offset inside the query.
var condition = name ? {
name: { [Op.iLike]: `%${name}%` },
color: { [Op.iLike]: `%${color}%` },
brand: { [Op.iLike]: `%${brand}%` },
} : null;
const paginate = (query, { page, pageSize }) => {
const offset = page * pageSize;
const limit = pageSize;
return {
...query,
offset,
limit,
};
};
model.findAll(
paginate(
{
where: condition
},
{ page, pageSize },
),
);
Also, you can refer to this here
you can use this
model.findAll({
limit: 5,
offset: 0,
where: {}, // conditions
});

Generate 1000 pdf with survey pdf

I'm trying to generate more than one thousand pdf files using surveyPDF.
The problem is that i can generate only 80 pdf files...
I'm passing an array with more than 1000 pdf to generate.
Code :
query.map(async items => {
const { generatePdf } = await import("~/lib/survey");
const filename = kebabCase(
`${campaign.title} - ${items.employee.fullName.toLowerCase()} -${moment().format("DD/MM/YYYY - HH:mm")} `
);
return generatePdf(campaign.template.body, items, filename, 210, 297);
});
The code which generate each pdfs :
import autoTable from "jspdf-autotable";
import { SurveyPDF, CommentBrick, CompositeBrick, PdfBrick, TextBrick } from "survey-pdf";
import { format } from "~/utils/date";
class AutoTableBrick extends PdfBrick {
constructor(question, controller, rect, options) {
super(question, controller, rect);
this.margins = {
top: controller.margins.top,
bottom: controller.margins.bot,
right: 30,
left: 30,
};
this.options = options;
}
renderInteractive() {
if (this.controller.doc.lastAutoTable && !this.options.isFirstQuestion) {
this.options.startY = this.yTop;
}
autoTable(this.controller.doc, {
head: [
[
{
content: this.question.title,
colSpan: 2,
styles: { fillColor: "#5b9bd5" },
},
],
],
margin: { ...this.margins },
styles: { fillColor: "#fff", lineWidth: 1, lineColor: "#5b9bd5", minCellWidth: 190 },
alternateRowStyles: { fillColor: "#bdd6ee" },
...this.options,
});
}
}
export async function generatePdf(json, data, filename, pdfWidth, pdfHeight) {
if (!json) {
return Promise.reject("Invalid json for pdf export");
}
for (const page of json.pages) {
page.readOnly = true;
}
const surveyPDF = new SurveyPDF(json, {
fontSize: 11,
format: [pdfWidth, pdfHeight],
commercial: true,
textFieldRenderAs: "multiLine",
});
surveyPDF.showQuestionNumbers = "off";
surveyPDF.storeOthersAsComment = false;
//TODO This does not work well with dynamic dropdown, bug declared
// surveyPDF.mode = "display";
surveyPDF.mergeData({ ...data, _: {} });
surveyPDF.onRenderQuestion.add(function(survey, options) {
const { bricks, question } = options;
if (question.getType() === "comment" && question.value && bricks.length > 0) {
for (const brick of bricks) {
if (brick.value) {
brick.value = question.value.replace(/\t/g, " ");
}
if (brick instanceof CompositeBrick) {
const { bricks } = brick;
for (const brick of bricks) {
if (brick instanceof CommentBrick) {
brick.value = question.value.replace(/\t/g, " ");
}
}
}
}
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
bricks,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "multipletext") {
const body = [];
let extraRows = 0;
let rows = question.getRows();
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
let { title, value, inputType } = rows[i][j];
if (inputType === "date") {
value = format(value);
}
if (typeof value === "string" && value.length > 0) {
const valueEstRows = value.match(/.{1,70}/g).length;
if (valueEstRows > 1) {
extraRows += valueEstRows;
}
}
body.push([title, value || "N/A"]);
}
}
//TODO Use SurveyHelper helperDoc do calculate the height of the auto table
const startY = point.yTop;
const height = 21.5 * (body.length + 1) + 8.5 * extraRows;
const isFirstQuestion = question.title === question.parent.questions[0].title;
options.bricks = [
new AutoTableBrick(question, controller, SurveyHelper.createRect(point, bricks[0].width, height), {
startY,
body,
isFirstQuestion,
}),
];
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "text") {
//Draw question background
const { default: backImage } = await import("~/public/assets/images/block.png");
const backWidth = SurveyHelper.getPageAvailableWidth(controller);
const backHeight = SurveyHelper.pxToPt(100);
const imageBackBrick = SurveyHelper.createImageFlat(point, null, controller, backImage, backWidth, backHeight);
options.bricks = [imageBackBrick];
point.xLeft += controller.unitWidth;
point.yTop += controller.unitHeight;
const oldFontSize = controller.fontSize;
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
//Draw text question text field border
let { default: textFieldImage } = await import("~/public/assets/images/input.png");
let textFieldPoint = SurveyHelper.createPoint(imageBackBrick);
textFieldPoint.xLeft += controller.unitWidth;
textFieldPoint.yTop -= controller.unitHeight * 3.3;
let textFieldWidth = imageBackBrick.width - controller.unitWidth * 2;
let textFieldHeight = controller.unitHeight * 2;
let imageTextFieldBrick = SurveyHelper.createImageFlat(
textFieldPoint,
null,
controller,
textFieldImage,
textFieldWidth,
textFieldHeight
);
options.bricks.push(imageTextFieldBrick);
textFieldPoint.xLeft += controller.unitWidth / 2;
textFieldPoint.yTop += controller.unitHeight / 2;
let textFieldValue = question.value || "";
if (textFieldValue.length > 90) {
textFieldValue = textFieldValue.substring(0, 95) + "...";
}
const textFieldBrick = await SurveyHelper.createBoldTextFlat(
textFieldPoint,
question,
controller,
textFieldValue
);
controller.fontSize = oldFontSize;
textFieldBrick.unfold()[0]["textColor"] = "#EFF8FF";
options.bricks.push(textFieldBrick);
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "radiogroup" || question.getType() === "rating") {
options.bricks = [];
const oldFontSize = controller.fontSize;
const titleLocation = question.hasTitle ? question.getTitleLocation() : "hidden";
let fieldPoint;
if (["hidden", "matrix"].includes(titleLocation)) {
fieldPoint = SurveyHelper.clone(point);
} else {
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
titleBrick.xLeft += controller.unitWidth;
titleBrick.yTop += controller.unitHeight * 2;
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
fieldPoint = SurveyHelper.createPoint(titleBrick);
fieldPoint.yTop += controller.unitHeight * 1.3;
}
//Draw checkbox question items field
const { default: itemEmptyImage } = await import("~/public/assets/images/unchecked.png");
const { default: itemFilledImage } = await import("~/public/assets/images/checked.png");
const itemSide = controller.unitWidth;
let imageItemBrick;
const choices = question.getType() === "rating" ? question.visibleRateValues : question.visibleChoices;
for (const choice of choices) {
const isItemSelected =
question.getType() === "rating" ? question.value === choice.value : choice === question.selectedItem;
imageItemBrick = SurveyHelper.createImageFlat(
fieldPoint,
null,
controller,
isItemSelected ? itemFilledImage : itemEmptyImage,
itemSide,
itemSide
);
options.bricks.push(imageItemBrick);
const textPoint = SurveyHelper.clone(fieldPoint);
textPoint.xLeft += itemSide + controller.unitWidth / 2;
textPoint.yTop += itemSide / 12;
const itemValue = choice.locText.renderedHtml;
const checkboxTextBrick = await SurveyHelper.createTextFlat(
textPoint,
question,
controller,
itemValue,
TextBrick
);
checkboxTextBrick.unfold()[0]["textColor"] = "#6a6772";
fieldPoint.yTop = imageItemBrick.yBot + SurveyHelper.GAP_BETWEEN_ROWS * controller.unitHeight;
options.bricks.push(checkboxTextBrick);
}
}
});
surveyPDF.onRenderFooter.add(function(survey, canvas) {
canvas.drawText({
text: canvas.pageNumber + "/" + canvas.countPages,
fontSize: 10,
horizontalAlign: "right",
margins: {
right: 12,
},
});
});
return await surveyPDF.raw(`./pdf/${filename}.pdf`);
}
The error :
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
I have already try to increase the node memory using $env:NODE_OPTIONS="--max-old-space-size=8192"

How to dynamically change the version from package.json?

I get version 1.0.1 (server_version) from the server
I compare what is in process.env.version === server_version
If this is the case, then I change process.env.version = server_version.
However, I just can't do it from the client side.
All this is needed to request an update from the user, that is, when a new version is released, then ask, and then do $router.go()
If you're using Vue-CLI - you can do the same as me:
// vue.config.js
module.exports =
{
chainWebpack: config =>
{
config.plugin('define')
.tap(args =>
{
args[0]['process.env'].BUILD_TIME = webpack.DefinePlugin.runtimeValue(Date.now, ['./package.json']);
args[0]['process.env'].VERSION = JSON.stringify(pk.version);
return args;
});
return config;
}
}
Then, in your public/index.html
<!DOCTYPE html>
<html>
<head>
.....
<template id="VERSION"><%= process.env.VERSION %></template>
.....
</html>
Then, in your src/main.js
import mixinVersion from './mixins/mixinVersion'
import { version } from '../package.json'
.....
new Vue({
mixins: [mixinVersion],
computed:
{
appVersion()
{
const buildTime = new Date(process.env.BUILD_TIME);
return version + ' (' + buildTime.toLocaleString('en', {
year: 'numeric',
day: 'numeric',
month: 'short',
hour: 'numeric',
minute: 'numeric',
}) + ')';
},
},
created()
{
this.firstVersionCheck();
}
});
Then in src/mixins/mixinVersion.js
import { version } from '#/../package.json';
const checkingPeriod = 200; // in seconds
function isNewerVersion(_old, _new)
{
// return true if SemVersion A is newer than B
const oldVer = _old.split('.');
const newVer = _new.split('.');
if (+oldVer[0] < +newVer[0]) return false;
if (+oldVer[0] > +newVer[0]) return true;
if (+oldVer[1] < +newVer[1]) return false;
if (+oldVer[1] > +newVer[1]) return true;
return +oldVer[2] > +newVer[2];
}
export default
{
data()
{
return {
newVersionExists: false,
timerVersion: null,
lastVersionCheck: null,
windowHiddenProp: '',
};
},
watch:
{
newVersionExists(newVal, oldVal)
{
// if the user decides to dismiss and not refresh - we must continue checking
if (oldVal && !newVal) this.scheduleVersion();
},
},
methods:
{
firstVersionCheck()
{
this.lastVersionCheck = Date.now();
// Set the name of the hidden property and the change event for visibility
let visibilityChange;
if (typeof document.hidden !== 'undefined')
{
// Opera 12.10 and Firefox 18 and later support
this.windowHiddenProp = 'hidden';
visibilityChange = 'visibilitychange';
}
else if (typeof document.msHidden !== 'undefined')
{
this.windowHiddenProp = 'msHidden';
visibilityChange = 'msvisibilitychange';
}
else if (typeof document.webkitHidden !== 'undefined')
{
this.windowHiddenProp = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
document.addEventListener(visibilityChange, this.handlePageVisibility, false);
this.scheduleVersion();
},
handlePageVisibility()
{
if (!document[this.windowHiddenProp])
{
// if too much time has passed in the background - immediately check for new version
if (Date.now() - this.lastVersionCheck > checkingPeriod * 1000)
{
if (this.timerVersion) clearTimeout(this.timerVersion);
this.checkVersion();
}
}
},
scheduleVersion()
{
// check for new versions
if (this.timerVersion) clearTimeout(this.timerVersion);
this.timerVersion = setTimeout(this.checkVersion, checkingPeriod * 1000); // check for new version every 3.3 minutes
},
checkVersion()
{
this.timerVersion = null;
fetch(process.env.BASE_URL + 'index.html', {
headers:
{
'X-SRS-Version': version,
}
}).then(response =>
{
if (response.status != 200) throw new Error('HTTP status = ' + response.status);
return response.text();
}).then(t =>
{
this.lastVersionCheck = Date.now();
const newVersion = t.match(/<template id="?VERSION"?>([^<]+)<\/template>/);
if (newVersion && newVersion[1])
{
if (isNewerVersion(newVersion[1], version))
{
if (!this.newVersionExists) // do not show multiple notifications
{
this.$snotify.confirm('There is a new version', 'New version', {
timeout: 0,
closeOnClick: false,
position: 'leftBottom',
buttons:
[
{
text: 'REFRESH',
action()
{
window.location.reload();
}
}
]
});
}
this.newVersionExists = true;
}
else this.scheduleVersion();
}
else this.scheduleVersion();
}).catch(err =>
{
if (navigator.onLine) console.error('Could not check for new version', err.message || err);
this.scheduleVersion();
});
},
}
};

Sequelize pagination

Using sequelize on my nodejs web app, I want to query posts using pagination (by date). Reading sequelize docs, they offer to use offset and limit.
Since I want to display the posts from new to old, I need to consider the date they were created. For example, if I limit the first query to 10 page, and before executing the second query a new post was created, the next query with offset of 10 will result a duplicate post from the last query.
How should I implement the pagination so it will support new entries?
The easiest way to do this is to use Sequelize's findAndCountAll
Post.findAndCountAll({
where: {...},
order: [...],
limit: 5,
offset: 0,
}).then(function (result) {
res.render(...);
});
Here, result has both the result of your query and count as result.rows and result.count. You can then increment the offset and use this for pagination.
Sequelize documentation for findAndCountAll
Try this:
const paginate = (query, { page, pageSize }) => {
const offset = page * pageSize;
const limit = pageSize;
return {
...query,
offset,
limit,
};
};
model.findAll(
paginate(
{
where: {}, // conditions
},
{ page, pageSize },
),
);
In order to avoid boilerplate code
If you want to have a stable pagination, don't paginate on row offset, since it's volatile, for the reason you mention.
You should aim for paginating on a value that is stable over time and use a where clause for filtering results. The best case would be if you have an auto-incrementing id, but the post date could also be reasonable.
Something like:
Post.findAll({
where: { createdDate: { $lt: previousDate },
limit: 10
})
You need to keep track of previousDate for this ofc. This approach also has some caveats, and you may need to combine it with client-side de-duplication.
Here is a blog post that probably has all the answers you need:
Pagination: You're (Probably) Doing It Wrong
With findAndCountAll here count is useful for pagination, from this total count we can limit as we want and also with async and await
let resAccidents = await ModalName.findAndCountAll({ where: { createdByID: employeeID }, offset: 0, limit: 10 });
this will return a count of total records as per where condition and 1st 10 records of it, then increase the value of offset to fetch further records.
You can simply do that
let limit = 10
let offset = 0 + (req.body.page - 1) * limit
Posts.findAndCountAll({
offset: offset,
limit: limit,
order: [
['date', 'ASC']
]
}).then(async result => {
return res.status(200).json({
status: true,
message: res.__('success'),
innerData: result
})
})
.catch(err => {
return validator.InvalidResponse(res, `${err}`)
})
Try this instead:
db.findAll({
offset: page_no,// your page number
limit:25,// your limit
This one solved my issue.
export const paginate = (query, schema) => {
let page = query.page ? query.page - 1 : 0;
page = page < 0 ? 0 : page;
let limit = parseInt(query.limit || 10);
limit = limit < 0 ? 10 : limit;
const offset = page * limit;
const where = {};
delete query.page;
delete query.limit;
Object.keys(schema).forEach((key) => {
schema[key] && query[key] ? (where[key] = query[key]) : null;
});
return {
where: where,
offset,
limit,
};
};
#Get()
findAll(#Query() query): unknown {
return this.model.findAll(paginate(query, {xx:1}));
}
/model?xx=yy&page=1&limit=5
var defered = Q.defer();
const offset = queryString.offset * queryString.limit;
const limit = queryString.limit;
var queryWhere = { class_id: { $ne: null }, section_id: { $ne: null } };
var searchClass = {};
var searchSection = {};
if (queryString) {
if (queryString.class && queryString.class !== "") {
searchClass = { class_id: { $eq: queryString.class } };
} else if (queryString.class && queryString.class === "") {
searchClass = { class_id: { $ne: null } };
}
if (queryString.section && queryString.section !== "") {
searchSection = { section_id: { $eq: queryString.section } };
} else if (queryString.section && queryString.section === "") {
searchSection = { section_id: { $ne: null } };
}
}
queryWhere = {
$and: [[searchClass], [searchSection]]
};
const schoolDB = require("../../db/models/tenant")(schema);
const Student = schoolDB.model("Student");
Student.findAll({
attributes: [
"id",
"first_name",
"last_name",
"profile_image_url",
"roll_number",
"emergency_contact_number"
],
offset: offset,
limit: limit,
where: queryWhere,
order: [["roll_number", "ASC"]]
})
.then(result => {
defered.resolve(result);
})
.catch(err => {
defered.reject(err);
});
Recommended using Sequelize's own operators
var defered = Q.defer();
const offset = queryString.offset * queryString.limit;
const limit = queryString.limit;
var queryWhere = { class_id: { $ne: null }, section_id: { $ne: null } };
var searchClass = {};
var searchSection = {};
if (queryString) {
if (queryString.class && queryString.class !== "") {
searchClass = { class_id: { $eq: queryString.class } };
} else if (queryString.class && queryString.class === "") {
searchClass = { class_id: { $ne: null } };
}
if (queryString.section && queryString.section !== "") {
searchSection = { section_id: { $eq: queryString.section } };
} else if (queryString.section && queryString.section === "") {
searchSection = { section_id: { $ne: null } };
}
}
queryWhere = {
$and: [[searchClass], [searchSection]]
};
const schoolDB = require("../../db/models/tenant")(schema);
const Student = schoolDB.model("Student");
Student.findAll({
attributes: [
"id",
"first_name",
"last_name",
"profile_image_url",
"roll_number",
"emergency_contact_number"
],
offset: offset,
limit: limit,
where: queryWhere,
order: [["roll_number", "ASC"]]
})
.then(result => {
defered.resolve(result);
})
.catch(err => {
defered.reject(err);
});

Resources