xxxxxxxxxx
import { Model, Document, Query } from 'mongoose';
class QueryBuilder<T extends Document> {
private query: Query<T[]>;
constructor(model: Model<T>) {
this.query = model.find();
}
search(searchTerm: string): this {
if (searchTerm) {
// Implement search logic based on the provided search term
this.query = this.query.regex(new RegExp(searchTerm, 'i'));
}
return this;
}
filter(filters: Record<string, any>): this {
// Implement filter logic based on the provided filters
// For example: this.query = this.query.where(filters);
return this;
}
paginate(page: number, limit: number): this {
// Implement pagination logic based on the provided page and limit
const skip = (page - 1) * limit;
this.query = this.query.skip(skip).limit(limit);
return this;
}
sort(sortBy: string, sortOrder: 'asc' | 'desc'): this {
// Implement sorting logic based on the provided sortBy and sortOrder
this.query = this.query.sort({ [sortBy]: sortOrder });
return this;
}
select(fields: string[]): this {
// Implement field limiting logic based on the provided fields
this.query = this.query.select(fields.join(' '));
return this;
}
execute(): Query<T[]> {
// Return the final executed query
return this.query;
}
}
export default QueryBuilder;
xxxxxxxxxx
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/4.8.3/typescript.min.js" integrity="sha512-ipipS8Je0Nf76mSbTGMnLwgpI023wQDvAoZQ90fEJ/5eqrVs0YpfTqjsa+EX44iT5IHThlAqsgq3L1l7lwZcpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
xxxxxxxxxx
typescript is javascript with syntax for types to aviod bugs in development,
autocompletion on object.
//install
npm i -g typescript //install globally
// to see if it is install
tsc --help
xxxxxxxxxx
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
xxxxxxxxxx
const user = {
firstName: "Angela",
lastName: "Davis",
role: "Professor"
}
console.log(user.firstName)
Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.2339Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.Try
xxxxxxxxxx
const user = {
firstName: "Angela",
lastName: "Davis",
role: "Professor",
}
console.log(user.name)
Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.
Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.