@htdangkhoa/google-ads
Version:
Google Ads API client for Node.js
66 lines (65 loc) • 1.94 kB
JavaScript
import deepmerge from 'deepmerge';
import { OrderDirection, QUERY } from './types.js';
export class QueryBuilder {
constructor() {
this._attributes = [];
this._table = '';
this._conditions = [];
this._orders = [];
this._limit = 0;
this._parameters = {};
}
select(...args) {
this._attributes.push(...args);
return this;
}
from(table) {
this._table = table;
return this;
}
where(...args) {
this._conditions.push(...args);
return this;
}
orderBy(...args) {
this._orders.push(...args);
return this;
}
limit(limit) {
this._limit = limit;
return this;
}
parameters(parameters) {
this._parameters = (deepmerge.all([this._parameters, parameters]));
return this;
}
build() {
const query = [];
if (this._attributes.length) {
query.push(QUERY.SELECT, this._attributes.join(', '));
}
if (this._table) {
query.push(QUERY.FROM, this._table);
}
if (this._conditions.length) {
query.push(QUERY.WHERE, this._conditions
.map((condition) => `${condition.attribute} ${condition.operator} ${condition.value}`)
.join(' AND '));
}
if (this._orders.length) {
query.push(QUERY.ORDER_BY, this._orders
.map((order) => `${order.attribute} ${order.direction || OrderDirection.ASC}`)
.join(', '));
}
if (this._limit) {
query.push(QUERY.LIMIT, this._limit);
}
const parameterKeys = Object.keys(this._parameters);
if (parameterKeys.length) {
query.push(QUERY.PARAMETERS, parameterKeys
.map((key) => `${key} = ${this._parameters[key]}`)
.join(', '));
}
return query.join(' ');
}
}