Skip to content

Commit

Permalink
Update types for subscriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
stwiname committed Nov 25, 2024
1 parent 3f980cc commit 9b73dbd
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions packages/query/src/graphql/plugins/PgSubscriptionPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import {hashName} from '@subql/utils';
import {PgIntrospectionResultsByKind} from '@subql/x-graphile-build-pg';
import {makeExtendSchemaPlugin, gql, embed} from 'graphile-utils';
import {DocumentNode} from 'graphql';

const filter = (event, args) => {
if (args.mutation && !args.mutation.includes(event.mutation_type)) {
Expand All @@ -15,6 +16,19 @@ const filter = (event, args) => {
return true;
};

function makePayload(entityType: string): {type: DocumentNode; name: string} {
const name = `${entityType}Payload`;
const type = gql`
type ${name} {
id: ID!
mutation_type: MutationType!
_entity: ${entityType}
}
`;

return {name, type};
}

export const PgSubscriptionPlugin = makeExtendSchemaPlugin((build) => {
const {inflection, pgIntrospectionResultsByKind} = build;

Expand All @@ -25,26 +39,26 @@ export const PgSubscriptionPlugin = makeExtendSchemaPlugin((build) => {
UPDATE
DELETE
}
type SubscriptionPayload {
id: ID!
mutation_type: MutationType!
_entity: JSON
}
`,
];

const resolvers: Record<string, any> = {};

// Generate subscription fields for all database tables
(pgIntrospectionResultsByKind as PgIntrospectionResultsByKind).class.forEach((table) => {
if (!table.namespace || table.name === '_metadata') return;

const field = inflection.allRows(table);
const type = inflection.tableType(table);

const {name: payloadName, type: payloadType} = makePayload(type);

const topic = hashName(table.namespace.name, 'notify_channel', table.name);
typeDefs.push(
gql`
${payloadType}
extend type Subscription {
${field}(id: [ID!], mutation: [MutationType!]): SubscriptionPayload
${field}(id: [ID!], mutation: [MutationType!]): ${payloadName}
@pgSubscription(
topic: ${embed(topic)}
filter: ${embed(filter)}
Expand All @@ -53,5 +67,8 @@ export const PgSubscriptionPlugin = makeExtendSchemaPlugin((build) => {
);
});

return {typeDefs};
return {
typeDefs,
resolvers,
};
});

0 comments on commit 9b73dbd

Please sign in to comment.