How to use the defaults function from pg

Find comprehensive JavaScript pg.defaults code examples handpicked from public code repositorys.

pg.defaults is a Node.js module that allows you to set default values for PostgreSQL client configuration options that can be overridden by environment variables or passed in options when creating a new client.

119
120
121
122
123
124
125
126
127
128
129
const startWorker = async (workerId) => {
  log.warn(`Starting worker ${workerId}`);


  const pgConfigs = {
    development: {
      user:     process.env.DB_USER || pg.defaults.user,
      password: process.env.DB_PASS || pg.defaults.password,
      database: process.env.DB_NAME || 'mastodon_development',
      host:     process.env.DB_HOST || pg.defaults.host,
      port:     process.env.DB_PORT || pg.defaults.port,
fork icon2
star icon4
watch icon2

+ 3 other calls in file

How does pg.defaults work?

pg.defaults works by creating a configuration object that can be pre-populated with default values for PostgreSQL client configuration options.

When you create a new PostgreSQL client with pg.Client, pg.Pool, or any other method provided by the pg module, the client will first check if the configuration option exists in the configuration object and use its value if available.

If not, the client will look for the option in the other sources (e.g., environment variables, passed in options) and use its value if available.

This allows you to set up a sensible default configuration for your PostgreSQL clients, but still give users the ability to customize it based on their specific needs.

Ai Example

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
const { Client } = require("pg");

// Set default values for PostgreSQL client configuration options
const defaults = {
  host: "localhost",
  port: 5432,
  user: "postgres",
  password: "secret",
  database: "myapp",
};

// Create a new PostgreSQL client with default configuration
const client = new Client(defaults);

// Connect to the database
client
  .connect()
  .then(() => {
    console.log("Connected to PostgreSQL database");
  })
  .catch((error) => {
    console.error("Error connecting to PostgreSQL database", error);
  });

// Query the database
client
  .query("SELECT * FROM users")
  .then((result) => {
    console.log(`Retrieved ${result.rowCount} rows from PostgreSQL database`);
  })
  .catch((error) => {
    console.error("Error querying PostgreSQL database", error);
  })
  .finally(() => {
    // Disconnect from the database
    client.end();
    console.log("Disconnected from PostgreSQL database");
  });

In this example, we first set default values for several PostgreSQL client configuration options using pg.defaults. We then create a new PostgreSQL client with the default configuration, connect to the database, and execute a query. Finally, we handle any errors that may occur and disconnect from the database when finished.