0

Is it possible to access pgSettings in a PostGraphile plugin, specifically makeExtendSchema? Here is my middleware:

app.use(
    postgraphile(
        process.env.DATABASE_URL,
        "public",
        {
            watchPg: true,
            classicIds: true,
            pgSettings: (req) => {
                if (req.headers.cookie) {
                    const cookies = cookie.parse(req.headers.cookie);
                    return {
                        'user.id': cookies['next-auth.session-token']
                    }
                }
                return;
            },
            appendPlugins: [require('./add-cookie-plugin')]
        }
    )
);

I want a plugin that adds the userId to each mutation, since it's in a cookie and I can't send it in the graphql payload. I saw pg is available, if I wanted an SQL command. Just want to know if the setting is already available:

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


module.exports = makeExtendSchemaPlugin(build => {

  const { pgSql: sql, inflection } = build;


  return {
    typeDefs: gql`
      extend type Query {
        userId: Int
      }
    `,
    resolvers: {
      Query: {
        async userId() {
          return // current_setting('user.id', true)
        },
      },
    },
  }
});
steve76
  • 302
  • 2
  • 9
  • 1
    You can use `additionalGraphQLContextFromRequest` then access it via the context argument (the third arg to a resolver). – Benjie Jun 12 '21 at 12:40

1 Answers1

0

additionalGraphQLContextFromRequest is great. But I would have to create the entire resolver. Instead I created a custom mutation:

CREATE FUNCTION public.create_row(content text)
RETURNS public.rows
AS $$
  INSERT INTO public.rows (user_id, content)
    SELECT u.user_id, content FROM users u JOIN sessions s ON u.user_id=s.user_id WHERE s.session_token = current_setting('user.id', true)
  RETURNING *;
$$ LANGUAGE sql VOLATILE STRICT;
steve76
  • 302
  • 2
  • 9