UNPKG

dfp-lib

Version:

This project hosts the Node.JS client library for the SOAP-based DFP API at Google.

103 lines (102 loc) 3.31 kB
"use strict"; const pql_1 = require("./pql"); const statement_1 = require("../soap/statement"); const mapUtils_1 = require("../../common/util/mapUtils"); const validationException_1 = require("../../common/lib/validationException"); class StatementBuilder { constructor() { this.valueMap = {}; } withBindVariableValue(key, value) { this.valueMap[key] = pql_1.Pql.createValue(value); return this; } toStatement() { const statement = new statement_1.Statement(); statement.query = this.buildQuery(); statement.values = mapUtils_1.MapUtils.getMapEntries(this.getBindVariableMap()); return statement; } static removeKeyword(clause, keyword) { keyword += ' '; if (clause.substr(0, keyword.length) === keyword) { clause = clause.substr(keyword.length); } return clause; } select(columns) { this._select = StatementBuilder.removeKeyword(columns, StatementBuilder.SELECT); return this; } from(table) { this._from = StatementBuilder.removeKeyword(table, StatementBuilder.FROM); return this; } where(conditions) { this._where = StatementBuilder.removeKeyword(conditions, StatementBuilder.WHERE); return this; } limit(count) { this._limit = count; return this; } offset(count) { this._offset = count; return this; } increaseOffsetBy(amount) { this._offset = (this._offset == null) ? amount : this._offset + amount; return this; } getOffset() { return this._offset; } removeLimitAndOffset() { this._offset = null; this._limit = null; return this; } orderBy(orderBy) { this._orderBy = StatementBuilder.removeKeyword(orderBy, StatementBuilder.ORDER_BY); return this; } getBindVariableMap() { return this.valueMap; } validateQuery() { if (this._offset != null && this._limit == null) { throw new validationException_1.ValidationException(StatementBuilder.OFFSET, this._offset, 'OFFSET cannot be set if LIMIT is not set.'); } } buildQuery() { this.validateQuery(); let statement = ""; if (this._select) { statement += StatementBuilder.SELECT + ' ' + this._select + ' '; } if (this._from) { statement += StatementBuilder.FROM + ' ' + this._from + ' '; } if (this._where) { statement += StatementBuilder.WHERE + ' ' + this._where + ' '; } if (this._orderBy) { statement += StatementBuilder.ORDER_BY + ' ' + this._orderBy + ' '; } if (this._limit) { statement += StatementBuilder.LIMIT + ' ' + this._limit + ' '; } if (this._offset) { statement += StatementBuilder.OFFSET + ' ' + this._offset + ' '; } return statement.trim(); } } StatementBuilder.SUGGESTED_PAGE_LIMIT = 500; StatementBuilder.SELECT = "SELECT"; StatementBuilder.FROM = "FROM"; StatementBuilder.WHERE = "WHERE"; StatementBuilder.LIMIT = "LIMIT"; StatementBuilder.OFFSET = "OFFSET"; StatementBuilder.ORDER_BY = "ORDER BY"; exports.StatementBuilder = StatementBuilder;