apollo-feature-requests
apollo-feature-requests copied to clipboard
Support subscriptions in SchemaLink
This issue on the old Apollo Link repo sums it up: there are cases (like testing, and demos) in which a SchemaLink user wants to add a subscription to their executable schema:
import { SchemaLink } from '@apollo/client/link/schema';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { addMocksToSchema, createMockStore } from '@graphql-tools/mock';
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { EventIterator } from 'event-iterator';
export interface User {
id: number;
name: string;
status?: 'DELETED';
};
const typeDefs = `
type User {
name: String
id: ID
}
type Subscription {
userAdded: User
}
schema {
subscription: Subscription
}
`;
// mock DB
const USERS: User[] = [
{ id: 1, name: 'Neil' }
];
const getNextUserId = () => Math.max(...USERS.map(x => x.id)) + 1;
function getIterator() {
return new EventIterator(
({ push }) => {
document.querySelector('button').addEventListener('click', push);
return () => document.querySelector('button').removeEventListener('click', push);
}
);
}
const schema = makeExecutableSchema({
typeDefs,
resolvers: {
Subscription: {
userAdded: {
subscribe: () => getIterator(),
resolve: () => makeNextUser()
}
}
}
});
const store = createMockStore({ schema });
function makeNextUser() {
const id = getNextUserId();
return {
name: store.get('User', id, 'name'),
id: store.get('User', id, 'id'),
};
}
export const client = new ApolloClient({
cache: new InMemoryCache(),
link: new SchemaLink({
schema: addMocksToSchema({
preserveResolvers: true,
store,
schema,
}),
}),
});
window.__APOLLO_CLIENT__ = client;
The above code looks like it should work, but it appears that the subscribe
callback under resolvers.Subscription.userAdded
never gets called at all.
The above-linked issue also links to a (now presumably out-of-date) Pull Request. Could that PR be reviewed/modified to bring subscriptions into SchemaLink?