Postgraphile -- makeExtendSchemaPlugin to add Viewer Type to schema -- Relay/Postgres

660 views Asked by At

I'm new to Relay, GraphQL and Postgres and I'm trying to extend the auto-generated schema that PostGraphile creates to include the Viewer Type which is a staple of Relay.

The example from their docs is probably enough for most people to work with but I'm having trouble fleshing it out. I basically want it to add a the field viewer: Viewer! to every Type.

Any help would be awesome.

const { makeExtendSchemaPlugin, gql } = require('graphile-utils');

const AddViewerPlugin = makeExtendSchemaPlugin(build => {
  // Get any helpers we need from `build`
  const { pgSql: sql, inflection } = build;

  return {
    typeDefs: gql`...`,
    resolvers: {
      /*...*/ 
    },
  };
});

module.exports = AddViewerPlugin;

My db has a public.person table and a private.person_account table but I hesitate to rename one of those viewer.

1

There are 1 answers

0
mpsido On BEST ANSWER

You use the "postgraphile" object to make your automatic schema detection. And use "makeExtendSchemaPlugin" to add extra resolvers to it.

makeExtendSchemaPlugin creates a plugin object that you can pass at the postgrahile object construction.

Here is an extract from the makeExtendSchemaPlugin page in the postgraphile documentation:

const { postgraphile } = require("postgraphile");
const { makeExtendSchemaPlugin, gql } = require("graphile-utils");const express = require("express");
const { convertUsdToAud } = require("ficticious-npm-library");
const MyForeignExchangePlugin = makeExtendSchemaPlugin(build => {  return {    typeDefs: gql`      extend type Product {        priceInAuCents: Int! @requires(columns: ["price_in_us_cents"])      }    `,    resolvers: {      Product: {        priceInAuCents: async product => {          // Note that the columns are converted to fields, so the case changes          // from `price_in_us_cents` to `priceInUsCents`          const { priceInUsCents } = product;          return await convertUsdToAud(priceInUsCents);        },      },    },  };});

const app = express();
app.use(
  postgraphile(process.env.DATABASE_URL, ["app_public"], {
    graphiql: true,
    appendPlugins: [MyForeignExchangePlugin],  })
);
app.listen(3030);