ts-db-helper
Version:
Simple ORM based on TypeScript
93 lines • 2.71 kB
JavaScript
import { QueryError } from '../../errors/query.error';
import { QueryManager } from '../../managers/query-manager';
/**
* @public
* @class QueryCount
*
* @description
* For design reasons this class should not be used directly.
* Prefer use {@link Count} function.
*
* @param T @extends DbHelperModel a model declared with table and column annotations
*
* @example
* ```typescript
* // count todos
* Count(Select(Todo).where({isDone: false}})).exec().subscribe((cout: number) => {
* // do something with the result...
* }, (err) => {
* // do something with the error...
* });
* ```
*
* @author Olivier Margarit
* @since 0.2
*/
var QueryCount = /** @class */ (function () {
/**
* @public
* @constructor create instance of QueryCount
* @param querySelect the query to count the result
*/
function QueryCount(querySelect) {
this.querySelect = querySelect;
}
/**
* @public
* @method build should be removed to be a part of the private API
*
* @return {DbQuery} of the query with the string part and
* clauses params.
*/
QueryCount.prototype.build = function () {
return this.querySelect.copy().projection(['count(*)']).build();
};
/**
* @public
* @method exec to execute the query and asynchronously retreive result.
*
* @return {Observable<number>} observable to subscribe and returning a count number as result
*/
QueryCount.prototype.exec = function () {
var dbQuery = this.build();
return QueryManager.getInstance().query(dbQuery).map(function (qr) {
if (qr.rows.length) {
var key = 'count(*)';
return qr.rows.item(0)[key];
}
else {
throw new QueryError('no result error...', dbQuery.query, dbQuery.params.join(', '));
}
});
};
return QueryCount;
}());
export { QueryCount };
/**
* @public
* @function Count
*
* @description
* function helper to count element that a query could return
*
* @param T @extends DbHelperModel a model declared with table and column annotations
*
* @example
* ```typescript
* // count todos
* Count(Select(Todo).where({isDone: false}})).exec().subscribe(count: number) => {
* // do something with the result...
* }, (err) => {
* // do something with the error...
* });
* ```
*
* @return {QueryCount<T>} instance
*
* @author Olivier Margarit
* @since 0.2
*/
export function Count(select) {
return new QueryCount(select);
}
//# sourceMappingURL=count.js.map