Skip to content

Adapters

Vitaly Tomilov edited this page Aug 6, 2020 · 76 revisions

This library can easily replace any custom implementation that's in use by many drivers today.

Ideally, those drivers should use this library internally, and provide their own specifics alongside. And while this may not be readily available, applications that use those drivers can still benefit from using connection-string internally.

Here're some examples of adapters, for the most popular drivers, converting a connection string into a proprietary connection string or object, as supported by the driver.

PostgreSQL

For node-postgres or pg-promise connection:

const cs = new ConnectionString('postgres://...your connection string...');

function get_PostgreSQL_connection() {
    return {
        host: cs.hostname,
        port: cs.port,
        database: cs.path?.[0],
        user: cs.user,
        password: cs.password,
        ssl: cs.params?.ssl ? Boolean(cs.params.ssl) : undefined,
        application_name: cs.params?.application_name

        /* etc, other parameters supported by the driver */

    };
}
MySQL

For mysql connection:

const cs = new ConnectionString('mysql://...your connection string...');

function get_MySQL_connection() {
    return {
        host: cs.hostname,
        port: cs.port,
        database: cs.path?.[0],
        user: cs.user,
        password: cs.password,
        timezone: cs.params?.timezone

        /* etc, other parameters supported by the driver */

    };
}

For more details see MySQL connection options.

MongoDB

MongoDB connection syntax is compatible with this library, while supporting string parameters only. But you can still use this library for injecting default values, or to access connection parameters.

const cs = new ConnectionString('mongodb://...your connection string...');

function get_MongoDB_connection() {
    // we can set defaults for the missing parameters here:
    cs.setDefaults({ user: 'def-user', password: 'def-password', /* etc...*/ });

    // MongoDB supports unusual "mongodb+srv" syntax for the protocol, rather than
    // the standard "mongodb:srv", so we use "+" for all spaces, for compatibility:
    return cs.toString({plusForSpace: true});
}

See also Compatibility.

MS-SQL

The latest node-mssql driver supports connection strings that are fully compatible with this library. But you can still use it for injecting default values in an easy way, and to be able to access connection parameters from the string independently.

const cs = new ConnectionString('mssql://...your connection string...');

function get_MSSQL_connection() {
    // we can set defaults for the missing parameters here:
    cs.setDefaults({ user: 'def-user', password: 'def-password', /* etc...*/ });

    return cs.toString();
}

Alternatively, you can create a connection config object, which is also supported by the driver.

Clone this wiki locally