Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of changing from simple subscriptions to (equivalent) custom subscriptions #269

Open
benjie opened this issue Apr 12, 2021 · 0 comments

Comments

@benjie
Copy link
Member

benjie commented Apr 12, 2021

// MySubscriptionPlugin.js

const base64 = (str) => Buffer.from(String(str)).toString("base64");
const nodeIdFromDbNode = (dbNode) => base64(JSON.stringify(dbNode));

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

const listenTopic = async (args, _context, _resolveInfo) => {
  const authCheckPassed = true; // TODO: implement your auth checks here
  if (authCheckPassed) {
    return `postgraphile:${args.topic}`;
  } else {
    throw new Error("You're not allowed to subscribe to this topic");
  }
};

function filterFn(payload, variables, context, info) {
  return true;
}

const MyPlugin = makeExtendSchemaPlugin((build) => {
  const { extend, newWithHooks, pgSql: sql, $$isQuery, resolveNode } = build;

  return {
    typeDefs: gql`
      type ListenPayload {
        query: Query
        relatedNode: Node
        relatedNodeId: ID
      }

      extend type Subscription {
        """
        Listen for any changes within the Platform with filter functionality
        """
        listen(topic: String!, filter: String): ListenPayload @pgSubscription(
          topic: ${embed(listenTopic)}
        )
      }
      `,

    resolvers: {
      Subscription: { listen: { resolve: (event) => event } },
      ListenPayload: {
        query: () => $$isQuery,
        relatedNodeId: (event) => nodeIdFromDbNode(event.__node__),
        async relatedNode(event, _args, resolveContext, resolveInfo) {
          const {
            getDataFromParsedResolveInfoFragment,
          } = resolveInfo.graphile.fieldContext;
          return resolveNode(
            nodeIdFromDbNode(event.__node__),
            build,
            { getDataFromParsedResolveInfoFragment },
            {},
            resolveContext,
            resolveInfo
          );
        },
      },
    },
  };
});

module.exports = MyPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant