UNPKG

pgmock2

Version:

An NPM module for mocking a connection to a PostgreSQL database.

264 lines (263 loc) 11 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var md5_1 = __importDefault(require("md5")); /** * An NPM module for mocking a connection to a PostgreSQL database. * @author Jason Favrod <mail@jasonfavrod.com> * @example * ``` * const PGMock2 = require('pgmock2'), * const pgmock = new PGMock2(); * ``` */ var PGMock2 = /** @class */ (function () { function PGMock2() { this.data = {}; this.latency = 20; } /** * Add a query, it's value definitions, and response to the * mock database. * @param {string} query An SQL query statement. * @param {array} valueDefs Contains the types of each value used * in the query. * @param {object} response The simulated expected response of * the given query. * @example * ``` * pgmock.add("SELECT * FROM employees WHERE id = $1", ['number'], { * rowCount: 1, * rows: [ * { id: 1, name: 'John Smith', position: 'application developer' } * ] * }); * ``` */ PGMock2.prototype.add = function (query, valueDefs, response) { this.data[this.normalize(query)] = { query: query, response: response, valDefs: valueDefs, }; }; /** * Get a simulated pg.Client or pg.Pool connection. * @namespace connect * @example const conn = pgmock.connect(); */ PGMock2.prototype.connect = function () { return __awaiter(this, void 0, void 0, function () { var connection; var _this = this; return __generator(this, function (_a) { connection = { /** * Simulate ending a pg connection. * @memberof connect * @example conn.release(); */ end: function () { return new Promise(function (res) { return res(); }); }, /** * Query the mock database. * @memberof connect * @param {string} sql An SQL statement. * @param {array} values Arguments for the SQL statement or * an empty array if no values in the statement. * @example conn.query('select * from employees where id=$1;', [0]) * .then(data => console.log(data)) * .catch(err => console.log(err.message)); * @example { * rowCount: 1, * rows: [ * { id: 1, name: 'John Smith', position: 'application developer' } * ] * } */ query: function (queryTextOrConfig, values) { return (_this.query(queryTextOrConfig, values)); }, /** * Simulate releasing a pg connection. * @memberof connect * @example conn.release(); */ release: function () { return new Promise(function (res) { return res(); }); }, }; return [2 /*return*/, new Promise(function (resolve) { setTimeout(function () { resolve(connection); }, _this.latency); })]; }); }); }; /** * Remove a query from the mock database. * @param {string} query An SQL statement added with the add method. * @returns {boolean} true if removal successful, false otherwise. */ PGMock2.prototype.drop = function (query) { return delete this.data[this.normalize(query)]; }; /** * Flushes the mock database. */ PGMock2.prototype.dropAll = function () { this.data = {}; }; PGMock2.prototype.end = function () { return new Promise(function (res) { return res(null); }); }; PGMock2.prototype.query = function (queryTextOrConfig, values) { if (typeof queryTextOrConfig === 'object') { return this.performQuery(queryTextOrConfig.text, values || queryTextOrConfig.values); } return this.performQuery(queryTextOrConfig, values); }; /** * Set the simulated network latency (default 20 ms). */ PGMock2.prototype.setLatency = function (latency) { this.latency = latency; }; /** * Return a string representation of the mock database. * @example * ``` * { * "3141ffa79e40392187830c52d0588f33": { * "query": "SELECT * FROM it.projects", * "valDefs": [], * "response": { * "rowCount": 3, * "rows": [ * { * "title": "Test Project 0", * "status": "pending", * "priority": "low", * "owner": "Favrod, Jason" * }, * { * "title": "Test Project 1", * "status": "pending", * "priority": "low", * "owner": "Favrod, Jason" * }, * ] * } * }, * "81c4b35dfd07db7dff2cb0e91228e833": { * "query": "SELECT * FROM it.projects WHERE title = $1", * "valDefs": ["string"], * "response": { * "rowCount": 1, * "rows": [ * { * "title": "Test Project 0", * "status": "pending", * "priority": "low", * "owner": "Favrod, Jason" * } * ] * } * } * } * ``` */ PGMock2.prototype.toString = function () { return JSON.stringify(this.data, null, 2); }; // Return the rawQuery in lowercase, without spaces nor // a trailing semicolon. PGMock2.prototype.normalize = function (rawQuery) { var norm = rawQuery.toLowerCase().replace(/\s/g, ''); return (0, md5_1.default)(norm.replace(/;$/, '')).toString(); }; PGMock2.prototype.performQuery = function (sql, values) { var _this = this; if (values === void 0) { values = []; } var norm = this.normalize(sql); var validQuery = this.data[norm]; return new Promise(function (resolve, reject) { if (validQuery && _this.validVals(values, validQuery.valDefs)) { setTimeout(function () { resolve(validQuery.response); }, _this.latency); } else { if (!validQuery) { setTimeout(function () { reject(new Error('invalid query: ' + sql + ' query hash: ' + norm)); }, _this.latency); } else { setTimeout(function () { reject(new Error('invalid values: ' + JSON.stringify(values))); }, _this.latency); } } }); }; PGMock2.prototype.validVals = function (values, defs) { var bool = true; if (values && values.length) { if (!defs.length || values.length !== defs.length) { throw Error('invalid values: Each value must have a corresponding definition.'); } values.forEach(function (val, i) { if (typeof (defs[i]) === 'string') { // Change bool to false if typeof val doesn't // match value definition string. if (typeof (val) !== defs[i]) { bool = false; } } else if (typeof (defs[i]) === 'function') { // Change bool to false if false returned from // value definition function. if (!defs[i](val)) { bool = false; } } }); } return bool; }; return PGMock2; }()); exports.default = PGMock2;