postgraphql

Get pgClient from postgraphile


I'm using the GraphQL API generator graphile as a middleware in an Express server.

I would like to create a custom http endpoint (not graphql) that makes a raw sql query to the postgres database. Is there some way to get the pgPool/pgQuery from the postgraphile middleware?

Basically I need to something like this:

app.use(postgraphile(pgConnectionString, pgSchemas, pgOptions));

app.get("/foo", (req, res) => {

    // get a pg query / pg client from the postgraphile middleware

    // make some query

    const result = await pgQuery.query(
        "SELECT ...."
    );

    // do something with result
});

Has anyone done something like this?

Or would it be better the other way, i.e. create a pgPool that is injected into postgraphile?

Cheers!


Solution

  • I solved this by injecting a pgPool into the postgraphile middleware. And the use the pgPool to query the database.

    // ...
    const pool = new Pool({
      connectionString: pgConnectionString,
    });
    pool.on("error", (err, client) => {
      console.error("Unexpected error on idle client", err);
    });
    app.use(postgraphile(pool, pgSchemas, pgOptions));