Skip to content

Commit

Permalink
implementing #109
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaly-t committed Mar 28, 2016
1 parent 4141dd6 commit f782ebc
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 7 deletions.
33 changes: 31 additions & 2 deletions lib/index.js
Expand Up @@ -80,8 +80,37 @@ var $npm = {
*/
function $main(options) {

if (!$npm.utils.isNull(options) && typeof options !== 'object') {
throw new TypeError("Invalid parameter 'options' specified.");
var invalidInit;
if (!$npm.utils.isNull(options)) {
if (typeof options === 'string') {
// Check for invalid initialization: it must not be a connection string.
var pg = require.cache[require.resolve('pg')];
var pcs = pg.require('pg-connection-string');
var cn = pcs.parse(options);
invalidInit = cn && cn.database !== options;
}
if (typeof options === 'object') {
// Check for invalid initialization: it must not be a connection object.
invalidInit = 'host' in options || 'database' in options;
} else {
if (!invalidInit) {
throw new TypeError("Invalid initialization options.");
}
}
}
if (invalidInit) {
// The most common mistake in using the library - trying to pass in a database
// connection object or string as the library's initialization object.
//
// Steps for using the library:
//
// 1. Initialize the library:
// var pgp = require('pg-promise')(/*initialization options*/);
// 2. Create database connection:
// var db = pgp(connection);
//
// If you skip the first step, you get this error.
throw new TypeError("Invalid library initialization: must initialize the library before creating a database connection.");
}

$npm.promise(options ? options.promiseLib : null);
Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "pg-promise",
"version": "3.4.2",
"version": "3.4.3",
"description": "PostgreSQL via promises",
"main": "lib/index.js",
"scripts": {
Expand Down
29 changes: 25 additions & 4 deletions test/entrySpec.js
Expand Up @@ -133,12 +133,33 @@ describe("Library entry function", function () {
});

describe("with invalid options parameter", function () {
var error = "Invalid parameter 'options' specified.";
it("must throw the correct error", function () {
var error = "Invalid initialization options.";
it("must throw an error", function () {
expect(function () {
header(123);
})
.toThrow(error);
}).toThrow(error);
expect(function () {
header('hello');
}).toThrow(error);
});
});

describe("with a connection instead of options", function () {
var error = "Invalid library initialization: must initialize the library before creating a database connection.";
it("must throw an error", function () {
expect(function () {
header('postgres://ops');
}).toThrow(error);
expect(function () {
header({
host: 'localhost'
});
}).toThrow(error);
expect(function () {
header({
database: 'myDB'
});
}).toThrow(error);
});
});

Expand Down

0 comments on commit f782ebc

Please sign in to comment.