@n1ru4l/socket-io-graphql-server
A layer for serving a GraphQL schema via a socket.io server. Supports Queries, Mutations, Subscriptions and Live Queries.
Note: Use @n1ru4l/socket-io-graphql-client
for executing operations against the server.
For a full setup check out the todo-example-server-socket-io.
Install Instructions
yarn add -E @n1ru4l/socket-io-graphql-server
API
registerSocketIOGraphQLServer
Registers the Socket.io GraphQL layer.
import { registerSocketIOGraphQLServer } from "@n1ru4l/socket-io-graphql-server";
import { Server as IOServer } from "socket.io";
const socketServer = new IOServer();
registerSocketIOGraphQLServer({
socketServer,
getParameter: ({
/* Socket.io instance of the client that executes the operation */ socket,
}) => ({
graphQLExecutionParameter: {
schema,
rootValue: {},
contextValue: {
socket,
},
},
}),
});
Recipies
Setting up live queries
You must also install @n1ru4l/in-memory-live-query-store
(or implement your own live query execute function).
yarn add -E @n1ru4l/in-memory-live-query-store
import { Server as IOServer } from "socket.io";
import { InMemoryLiveQueryStore } from "@n1ru4l/in-memory-live-query-store";
import { NoLiveMixedWithDeferStreamRule } from "@n1ru4l/graphql-live-query";
import { validate, specifiedRules } from "graphql";
const socketServer = new IOServer()
const liveQueryStore = new InMemoryLiveQueryStore();
const validationRules = [...specifiedRules, NoLiveMixedWithDeferStreamRule];
registerSocketIOGraphQLServer({
socketServer,
getParameter: ({ socket }) => ({
execute: liveQueryStore.execute,
validationRules,
graphQLExecutionParameter: {
schema,
rootValue:,
contextValue: {
socket,
liveQueryStore,
},
},
}),
});
Lazy Socket Authentication
Sometimes you only want to permit a socket executing stuff after authentication.
import { Server as IOServer } from "socket.io";
const socketServer = new IOServer();
const graphQLServer = registerSocketIOGraphQLServer({
socketServer,
getParameter: () => ({
graphQLExecutionParameter: {
schema,
rootValue,
contextValue: {
liveQueryStore,
},
},
}),
isLazy: true,
});
socketServer.on("connect", (socket) => {
socket.on("auth", (message) => {
if (checkAuth(message)) {
graphQLServer.registerSocket(socket);
}
});
});
Persisted Operations
import { Server as IOServer } from "socket.io";
import { InMemoryLiveQueryStore } from "@n1ru4l/graphql-live-query-store";
const persistedOperations = {
"1": "query { ping }"
"2": "mutation { ping }"
}
const socketServer = new IOServer();
const graphqlServer = registerSocketIOGraphQLServer({
socketServer,
getParameter: ({ socket, graphQLPayload }) => ({
graphQLExecutionParameter: {
schema,
rootValue:,
contextValue: {
socket,
},
source: persistedOperations[graphQLPayload.source]
},
}),
});
Destroy GraphQL Server
const server = registerSocketIOGraphQLServer({
socketServer,
getParameter: ({ socket }) => ({
graphQLExecutionParameter: {
schema,
rootValue,
contextValue: {
liveQueryStore,
},
},
}),
});
server.destroy();