Nested order_by in sequelize - node.js

I have to implement Nested orderby using sequelize but its not working below is my code
This whole code is working for me but I need to add sorting for a column reported_by which is present in Ticket table by reported_user_id name.
Below given images shows the hierarchy of database
TicketAssignment Table
Ticket Table
User table
TicketAssignment Table - ticket_id(FK) -> Ticket Table - id(PK)
Ticket Table - reported_user_id(FK) -> User Table - id(PK)
[let query = req.body.q;
let err, tickets;
let whereObj = {};
if (req.body.statusForTicket > 0) {
whereObj.status = 3;
} else {
whereObj.status = { [Op.in]: [0, 1, 2, 4, 5] };
}
if (req.user.role_id == 9) {
whereObj.suppport_company_id = req.user.company_id;
} else {
whereObj.engineer_user_id = req.user.id;
}
let whereObjInc = {};
if (query.trim() != "") {
whereObjInc.title = { [Op.like]: '%' + query.trim() + '%' };
}
if (req.body.date_from !== -1 && req.body.date_to !== -1) {
if (req.body.date_from != "") {
whereObjInc.createdAt = { [Op.gte]: req.body.date_from };
}
if (req.body.date_to != "") {
whereObjInc.createdAt = { [Op.lte]: req.body.date_from };
}
if (req.body.date_to != "" && req.body.date_from != "") {
whereObjInc.createdAt = { [Op.between]: [req.body.date_from, req.body.date_to] };
}
}
if (req.body.is_archive !== -1) {
whereObjInc.is_archive = req.body.is_archive;
}
let customOrder = [[order_by, order_by_ASC_DESC]];
if (order_by == 'title') {
customOrder = [[{ model: Ticket }, order_by, order_by_ASC_DESC]];
}
let orderByCondition = [[order_by, order_by_ASC_DESC]];
if (order_by == 'company') {
orderByCondition = [[{ model: Company, as: 'reported', }]];
//orderByCondition = [[{ model: Company, as: 'reported' }, 'company_name', order_by_ASC_DESC]];
}
if (order_by == 'accountable') {
orderByCondition = [[{ model: Company, as: 'accountable' }, 'company_name', order_by_ASC_DESC]];
}
if (order_by == 'reported_by') {
orderByCondition = [[{ model: Ticket},[{ model: User }, 'first_name', order_by_ASC_DESC]]];
}
let order_type = ['company', 'accountable', 'reported_by'];
if (order_type.includes(order_by)) {
[err, tickets] = await to(TicketAssignment.findAll({
where: whereObj,
include: [{ model: Ticket, where: whereObjInc }],
limit: limit,
offset: offset,
order: orderByCondition,
}));
}

Try it from your self. Try it from your self.

Related

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 display shop timing in a week nodejs

I have a key array of objects which user have for days and their timings for their shop i.e
user A -
{
"name" : "shop1",
"timings" : [
{
"Monday" : "10am to 7pm"
},
{
"Thursday" : "Closed"
},
{
"Friday" : "9am to 6pm"
},
{
"Sunday" : "Closed"
},
{
"Wednesday" : "10am to 7pm"
},
{
"Tuesday" : "10am to 7pm"
},
{
"Saturday" : "10am to 7pm"
}
]}
Now I need to show these timing by days in frontend i.e
Monday-Saturday:9am to 7pm, Thursday,Sunday: Closed
So far I've tried to loop them and searched all days which are closed i.e
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}
let closedDays = filterByValue(element.timings, 'Closed')
console.log("whtt",closedDays); // [{name: 'Lea', country: 'Italy'}]
let res = closedDays.map(x => Object.keys(x)[0]);
but for open days I can't figure out any suitable solution which can be used here. It would be a great help if you suggest something
const timings = [{"Monday": "10am to 7pm"}, {"Thursday": "Closed"}, {"Friday": "9am to 6pm"}, {"Sunday": "Closed"}, {"Wednesday": "10am to 7pm"}, {"Tuesday": "10am to 7pm"}, {"Saturday": "10am to 7pm"}];
const weekDaysInOrder = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
//Step1 little change list of objects
const newTimings = changeTimingsStructure(timings);
let obj = {}
sortTimings(newTimings).forEach(el => {
if (el.timing in obj) {
const maxIndex = Math.max(...obj[el.timing].map(el => el.indexOfDay));
if (maxIndex + 1 < el.indexOfDay && el.timing !== 'Closed') {
obj = pushToObjectArr(el.timing + '-v2', el, obj);
} else {
obj = pushToObjectArr(el.timing, el, obj);
}
} else {
obj = pushToObjectArr(el.timing, el, obj);
}
})
displayTimings(obj);
function changeTimingsStructure(timings) {
const newTimings = [];
timings.forEach(day => {
const dayName = Object.keys(day)[0]
const timing = day[dayName];
newTimings.push({
day: dayName,
timing,
indexOfDay: weekDaysInOrder.findIndex(dayInWeek => dayInWeek === dayName)
})
})
return newTimings;
}
function sortTimings(timings) {
return timings.sort(((a, b) => a.indexOfDay - b.indexOfDay));
}
function pushToObjectArr(key, el, obj) {
if (key in obj) {
obj[key].push(el);
} else {
obj[key] = [el]
}
return obj
}
function displayTimings(obj) {
let closedText = '';
for (const groupOfDays in obj) {
if (groupOfDays !== 'Closed') {
if (obj[groupOfDays].length > 1) {
console.log(`${obj[groupOfDays][0].day} - ${obj[groupOfDays][obj[groupOfDays].length - 1].day}: ${groupOfDays}`);
} else {
console.log(`${obj[groupOfDays][0].day}: ${obj[groupOfDays][0].timing}`);
}
} else {
closedText = `${obj[groupOfDays].map(dayObj => dayObj.day).join(', ')}: Closed`;
}
}
console.log(closedText);
}
Try this, final output:
Here I have created this utility in order to format the input as per your expected output.
let data = {name:'shop1',timings:[{Monday:'10am to 7pm'},{Thursday:'Closed'},{Friday:'9am to 6pm'},{Sunday:'Closed'},{Wednesday:'10am to 7pm'},{Tuesday:'10am to 7pm'},{Saturday:'10am to 7pm'}]};
const formatData = data => {
return data.reduce(
(result, d) => {
const value = Object.values(d)[0];
const key = Object.keys(d)[0];
if (value === 'Closed') {
result.closed.days.push(key);
if (!result.closed.values) {
result.closed.value = value;
}
} else {
result.open.days.push(key);
result.open.timings.push(value);
}
return result;
},
{
closed: { days: [], value: '' },
open: { days: [], timings: [] },
}
);
};
const formattedData = formatData(data.timings);
const formatTimings = timings => {
const formattedTimings= timings.reduce((result, time) => {
const times = time
.split('to')
.map(t => parseInt(t.replace(/\D+/g, '')))
.filter(Boolean);
result.from.push(times[0]);
result.to.push(times[1]);
return result
}, {from :[], to: []});
return `${Math.min(...formattedTimings.from)}am to ${Math.max(...formattedTimings.to)}pm`
};
const openDaysTimings = formatTimings(formattedData.open.timings);
const displayTimings = (days, time) => {
return `${days.join(", ")}: ${time}`
}
console.log(displayTimings(formattedData.closed.days, formattedData.closed.value));
console.log(displayTimings(formattedData.open.days, openDaysTimings));

How to dynamically generate schema for cube.js?

I have been working on a project to generate configurable dashboards.
so i have to generate schema dynamically based on an api request. is there any way to do that?
it will be very helpful if there is any working example!
There's an asyncModule function for this scenario. You can check example below:
const fetch = require('node-fetch');
const Funnels = require('Funnels');
asyncModule(async () => {
const funnels = await (await fetch('http://your-api-endpoint/funnels')).json();
class Funnel {
constructor({ title, steps }) {
this.title = title;
this.steps = steps;
}
get transformedSteps() {
return Object.keys(this.steps).map((key, index) => {
const value = this.steps[key];
let where = null
if (value[0] === PAGE_VIEW_EVENT) {
if (value.length === 1) {
where = `event = '${value[0]}'`
} else {
where = `event = '${value[0]}' AND page_title = '${value[1]}'`
}
} else {
where = `event = 'se' AND se_category = '${value[0]}' AND se_action = '${value[1]}'`
}
return {
name: key,
eventsView: {
sql: () => `select * from (${eventsSQl}) WHERE ${where}`
},
timeToConvert: index > 0 ? '30 day' : null
}
});
}
get config() {
return {
userId: {
sql: () => `user_id`
},
time: {
sql: () => `time`
},
steps: this.transformedSteps
}
}
}
funnels.forEach((funnel) => {
const funnelObject = new Funnel(funnel);
cube(funnelObject.title, {
extends: Funnels.eventFunnel(funnelObject.config),
preAggregations: {
main: {
type: `originalSql`,
}
}
});
});
})
More info: https://cube.dev/docs/schema-execution-environment#async-module

How to create Pagination with vue-table2?

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>

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