All files / src/connection connection-config.ts

100% Statements 38/38
100% Branches 60/60
100% Functions 16/16
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                                                  815x                 807x                 806x 806x 806x 791x   15x     806x     22x           815x 815x 2x       812x       815x 815x 17x   798x 815x                         794x 794x 1x   793x 793x 793x                     798x       830x 9104x         1635x                         37x       158x           828x 2x   826x       828x 828x 828x                               826x 826x                
import type { PoolConfig } from 'pg';
import type {
  ConnectionConfig as ConnectionSettings,
  ReplicationMember,
  SequelizeOptions,
} from './options.ts';
 
type ConstructorArgs =
  | readonly [SequelizeOptions?]
  | readonly [string, SequelizeOptions?]
  | readonly [string, string | null | undefined, (string | null | undefined)?, SequelizeOptions?];
 
/**
 * Connection configuration of a `Sequelize` instance: normalizes the overloaded Sequelize v6
 * constructor arguments and derives the `pg` pool configurations (writer and read replicas).
 */
export class ConnectionConfig {
  /** Normalized constructor options. */
  readonly options: SequelizeOptions;
 
  /**
   * @param args - Arguments of the `Sequelize` constructor (URI, database / username / password, options).
   * @throws Error for a non-postgres URI or dialect.
   */
  constructor(args: ConstructorArgs) {
    this.options = ConnectionConfig.#parse(args);
  }
 
  /**
   * Connection settings exposed as `sequelize.config`.
   *
   * @returns Database, user name, password, host and port.
   */
  settings(): ConnectionSettings {
    return ConnectionConfig.#settings(this.options);
  }
 
  /**
   * Pool configurations of the writer and the readers (no readers without `replication`).
   *
   * @returns Writer and reader `pg` pool configurations.
   */
  replicationPoolConfigs(): Readonly<{ write: PoolConfig; read: readonly PoolConfig[] }> {
    const options = this.options;
    const replication = options.replication;
    if (replication === undefined) {
      return { write: ConnectionConfig.#poolConfig(options), read: [] };
    }
    const readers: readonly ReplicationMember[] = Array.isArray(replication.read)
      ? replication.read
      : [replication.read as ReplicationMember];
    return {
      write: ConnectionConfig.#poolConfig(ConnectionConfig.#withMember(options, replication.write)),
      read: readers.map((member) =>
        ConnectionConfig.#poolConfig(ConnectionConfig.#withMember(options, member)),
      ),
    };
  }
 
  static #parse(args: ConstructorArgs): SequelizeOptions {
    const options = ConnectionConfig.#merge(args);
    if (options.dialect !== undefined && options.dialect !== 'postgres') {
      throw new Error(
        `postgrelize supports only the postgres dialect, got ${String(options.dialect)}`,
      );
    }
    return options;
  }
 
  static #merge(args: ConstructorArgs): SequelizeOptions {
    const [first, second, third, fourth] = args;
    if (first === undefined || typeof first === 'object') {
      return first ?? {};
    }
    const secondOptions = typeof second === 'object' && second !== null ? second : {};
    return ConnectionConfig.#isUri(first)
      ? { ...secondOptions, ...ConnectionConfig.#fromUri(first) }
      : {
          ...(fourth ?? secondOptions),
          ...ConnectionConfig.#definedOnly({
            database: first,
            username: typeof second === 'string' ? second : undefined,
            password: typeof third === 'string' ? third : undefined,
          }),
        };
  }
 
  static #fromUri(uri: string): SequelizeOptions {
    const url = new URL(uri);
    if (!['postgres:', 'postgresql:'].includes(url.protocol)) {
      throw new Error(`postgrelize supports only postgres:// connection URIs, got ${url.protocol}`);
    }
    const database = decodeURIComponent(url.pathname.replace(/^\//, ''));
    const sslmode = url.searchParams.get('sslmode');
    return {
      host: url.hostname,
      ...(url.port === '' ? {} : { port: Number(url.port) }),
      ...(database === '' ? {} : { database }),
      ...(url.username === '' ? {} : { username: decodeURIComponent(url.username) }),
      ...(url.password === '' ? {} : { password: decodeURIComponent(url.password) }),
      ...(sslmode === null || sslmode === 'disable' ? {} : { ssl: true }),
    };
  }
 
  static #isUri(value: string): boolean {
    return /^[a-z]+:\/\//i.test(value);
  }
 
  static #definedOnly<T extends object>(value: T): T {
    return Object.fromEntries(
      Object.entries(value).filter(([, item]) => item !== undefined && item !== null),
    ) as T;
  }
 
  static #settings(options: SequelizeOptions): ConnectionSettings {
    return {
      database: options.database,
      username: options.username,
      password: options.password,
      host: options.host ?? 'localhost',
      port: options.port ?? 5432,
    };
  }
 
  static #withMember(
    options: SequelizeOptions,
    member: ReplicationMember | undefined,
  ): SequelizeOptions {
    return member === undefined
      ? options
      : {
          ...options,
          ...Object.fromEntries(Object.entries(member).filter(([, value]) => value !== undefined)),
        };
  }
 
  // A UTC offset or an IANA zone name: it is passed as a libpq startup option, so no spaces.
  static #timezone(timezone: string): string {
    if (!/^(?:[+-]\d{2}:\d{2}|[A-Za-z][\w+\-/]*)$/.test(timezone)) {
      throw new Error(`Invalid timezone: ${timezone}`);
    }
    return timezone;
  }
 
  static #poolConfig(options: SequelizeOptions): PoolConfig {
    const config = ConnectionConfig.#settings(options);
    const timezone = ConnectionConfig.#timezone(options.timezone ?? '+00:00');
    return ConnectionConfig.#definedOnly({
      host: config.host,
      port: config.port,
      database: config.database,
      user: config.username,
      password: config.password,
      ssl: options.ssl,
      ...ConnectionConfig.#poolLimits(options),
      ...options.dialectOptions,
      options: [`-c TimeZone=${timezone}`, options.dialectOptions?.options]
        .filter(Boolean)
        .join(' '),
    });
  }
 
  static #poolLimits(options: SequelizeOptions): PoolConfig {
    const pool = options.pool ?? {};
    return {
      max: pool.max ?? 5,
      idleTimeoutMillis: pool.idle ?? 10_000,
      connectionTimeoutMillis: pool.acquire ?? 60_000,
      maxUses: pool.maxUses,
    };
  }
}