Skip to content

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

@benjie

Description

@benjie
// 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;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions