Skip to content

Instantly share code, notes, and snippets.

@e06widu
Created July 14, 2020 02:26
Show Gist options
  • Save e06widu/9c6beb0fb54ebb51f9685e5946bdb533 to your computer and use it in GitHub Desktop.
Save e06widu/9c6beb0fb54ebb51f9685e5946bdb533 to your computer and use it in GitHub Desktop.
import { Sequelize } from 'sequelize';
import { ConfigurationManager } from '../config';
export class DbConnector {
private static connectorInstance: DbConnector;
private readonly connection: Sequelize;
/**
* Returns an instance of DBConnector, which might or might not have been synced with the DB.
* It is currently the user"s prerogative to connect to the database.
*/
static getSingletonInstance(): DbConnector {
return DbConnector.connectorInstance = new DbConnector();
}
/**
* Returns the result set if rows exist, else null
* @param spQuery Sp with params
* @param parameterValues param values as json object
*/
async executeQuery<T>(spQuery: string, parameterValues: any, minimumNumberOfRows = 1): Promise<Array<T>> {
return new Promise<Array<T>>((resolve, reject) => {
this.connection.query(spQuery, { replacements: parameterValues }).then(([results]: Array<any>) => {
const hasRows = this.doesQueryHaveResults(results, minimumNumberOfRows);
resolve(hasRows ? (JSON.parse(JSON.stringify(results)) as Array<T>) : undefined as any);
}).catch(reject);
});
}
/**
* Returns the result of the query
* Note: All SPs return a value for a create/update, hence there is no need to check for number of rows returned.
* @param spQuery Sp with params
* @param parameterValues param values as json object
*/
async executeUpdate<T>(spQuery: string, parameterValues: any): Promise<Array<T>> {
return new Promise<Array<T>>((resolve, reject) => {
this.connection.query(spQuery, { replacements: parameterValues }).then(([results]: Array<any>) => {
resolve(JSON.parse(JSON.stringify(results)) as Array<T>);
}).catch(reject);
});
}
/**
* Checking the executed quary results
* @param results Result json
* @param minimumNumberOfRows minimum number of rows
*/
doesQueryHaveResults = (results: any, minimumNumberOfRows: number) => results && (results.length >= minimumNumberOfRows);
private constructor() {
this.connection = new Sequelize(ConfigurationManager.getSingletonInstance().connectionString, {
dialectOptions: {
options: {
encrypt: true
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment