postgraphile-core
This module is the compatibility between the web layer of
PostGraphile and the GraphQL schema
built with Graphile Engine. It loads the relevant graphile-build-pg
plugins
and augments the inflector depending on the PostGraphile options provided.
Unless you want to use the low-level API you probably want to go to the
PostGraphile (previously 'PostGraphQL') repository instead:
https://github.com/graphile/postgraphile
It's suitable to use this module in your own application, but please be aware you
need to bring your own security in the form of an authenticated pgClient
(see
below).
For more information about PostGraphile and Graphile Engine please see the
documentation at graphile.org.
createPostGraphileSchema(pgConfig, schemas, options)
This is the function you're most likely to use in production, it will return
a promise to a GraphQL schema. You are responsible in for implementing
security by passing a pre-authenticated pgClient
inside the GraphQL
context
when you resolve a GraphQL query or mutation.
Example:
const schema = await createPostGraphileSchema(
process.env.DATABASE_URL,
["users_schema", "posts_schema"],
{
dynamicJson: true,
pgJwtSecret: process.env.JWT_SECRET,
pgJwtTypeIdentifier: "users_schema.jwt_type",
}
);
Full example:
const { createPostGraphileSchema } = require("postgraphile-core");
const { graphql } = require("graphql");
const pg = require("pg");
const pgPool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
});
async function runQuery(query, variables) {
const schema = await createPostGraphileSchema(
process.env.DATABASE_URL,
["app_public"],
{
dynamicJson: true,
pgJwtSecret: process.env.JWT_SECRET,
pgJwtTypeIdentifier: "users_schema.jwt_type",
}
);
const pgClient = await pgPool.connect();
await pgClient.query("begin");
try {
await pgClient.query(`select
set_config('role', 'postgraphile_user', true),
set_config('jwt.claims.user_id', '27', true)
`);
return await graphql(
schema,
query,
null,
{
pgClient: pgClient,
} ,
variables
);
} finally {
await pgClient.query("commit");
await pgClient.release();
}
}
runQuery(
"query MyQuery { allPosts { nodes { id, title, author: userByAuthorId { username } } } }"
)
.then(result => {
console.dir(result);
pgPool.end();
})
.catch(e => {
console.error(e);
process.exit(1);
});
To see how this works in a real application, check out
withPostGraphileContext
in
PostGraphile
watchPostGraphileSchema(pgConfig, schemas, options, onNewSchema)
This function is useful in development; it returns a promise that resolves to a
release
function that you can call to stop watching. The onNewSchema
callback will be called every time a new schema is generated, and it is
guaranteed to be called before the returned promise resolves. Other than the
additional onNewSchema
option, the options are identical to that of
createPostGraphileSchema
above.