UNPKG

zumito-db

Version:

Multi-driver database abstraction layer with decorator-based models

65 lines (64 loc) 1.6 kB
export class QueryBuilder { ir; driver; constructor(driver, collection) { this.driver = driver; this.ir = { collection, type: 'find', where: [], }; } where(field, operator, value) { this.ir.where.push({ field, operator, value, logic: 'and' }); return this; } andWhere(field, operator, value) { this.ir.where.push({ field, operator, value, logic: 'and' }); return this; } orWhere(field, operator, value) { this.ir.where.push({ field, operator, value, logic: 'or' }); return this; } select(fields) { this.ir.select = fields; return this; } sort(field, dir) { if (!this.ir.sort) this.ir.sort = []; this.ir.sort.push({ field, dir }); return this; } limit(n) { this.ir.limit = n; return this; } offset(n) { this.ir.offset = n; return this; } populate(relation) { if (!this.ir.populate) this.ir.populate = []; this.ir.populate.push(relation); return this; } async exec() { return this.driver.find(this.ir.collection, this.ir); } async first() { const results = await this.driver.find(this.ir.collection, { ...this.ir, limit: 1, }); return results.length > 0 ? results[0] : null; } async count() { return this.driver.count(this.ir.collection, this.ir); } toIR() { return { ...this.ir }; } }