T-Effieciency Flashcards

(2 cards)

1
Q

To efficiently handle query options for all API resources, how do we store them?

A

We store them in a class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Create the Query Class.

A

class QueryFeatures {
constructor(query, queryString) {
this.query = query;
this.queryString = queryString;
}

filter() {
let obj = { …this.queryString };
const exclude = [“page”, “sort”, “limit”, “fields”];

exclude.forEach((field) => {
  delete obj[field];
});

obj = JSON.stringify(obj).replace(/\b(gte|gt|lte|lt)\b/g, (word) => {
  return `\$\${word}`;
});

obj = JSON.parse(obj);

this.query = this.query.find(obj);

return this;   }

sort(defaultSort) {
if (this.queryString.sort) {
const split = this.queryString.sort.split(“,”).join(“ “);
this.query = this.query.sort(split);
} else {
this.query = this.query.sort(${defaultSort});
}

return this;   }

limitingFields(unawantedFeild) {
if (this.queryString.fields) {
const fields = this.queryString.fields.split(“,”).join(“ “);
this.query = this.query.select(fields);
} else {
this.query = this.query.select(-${unawantedFeild});
}

return this;   }

pagination(defaultPage, defaultLimit) {
const page = Number(this.queryString.page) || defaultPage;
const limit = Number(this.queryString.limit) || defaultLimit;
const skip = (page - 1) * limit;

this.query = this.query.skip(skip).limit(limit);

return this;   } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly