From 215bf1617d8440f93d0b5715ca02b4c011cafd2e Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Sat, 23 Nov 2019 19:31:23 +0100 Subject: [PATCH] Add count method --- src/helpers/DatabaseHelper.ts | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/helpers/DatabaseHelper.ts b/src/helpers/DatabaseHelper.ts index 1f62f6a..e229726 100644 --- a/src/helpers/DatabaseHelper.ts +++ b/src/helpers/DatabaseHelper.ts @@ -21,6 +21,11 @@ export interface QueryInformation { limit ?: number, } +export interface CountQueryInformation { + table: string, + where ?: Object +} + export class DatabaseHelper { private static connection : Connection; @@ -188,4 +193,40 @@ export class DatabaseHelper { }); }) } + + /** + * Perform a COUNT query on the database + * + * @param info Information about the count query + */ + static async Count(info: CountQueryInformation) : Promise { + + let sql = "SELECT COUNT(*) as count FROM " + info.table; + let args = []; + + if(info.where) { + sql += " WHERE "; + + for (const key in info.where) { + if (info.where.hasOwnProperty(key)) { + const value = info.where[key]; + sql += "AND " + key + " = ? "; + args.push(value); + } + } + + sql = sql.replace("WHERE AND", "WHERE"); + } + + return await new Promise((r, e) => { + this.connection.query(sql, args, (err, results, f) => { + if(err){ + e(err); + return; + } + + r(results[0].count); + }) + }); + } } \ No newline at end of file