Skip to content

Commit

Permalink
Add support for graphql subscriptions & generate random msgs
Browse files Browse the repository at this point in the history
  • Loading branch information
mallocator committed Nov 18, 2023
1 parent 8054377 commit 254cad6
Show file tree
Hide file tree
Showing 3 changed files with 5,152 additions and 2,005 deletions.
81 changes: 68 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@
* This is the entry point for the GraphQL API plugin. Here we specify the GraphQL schema and resolvers.
*/

import {ApolloServer, gql} from 'apollo-server';
import express from 'express';
import cors from 'cors';
import {ApolloServer, gql} from 'apollo-server-express';
import {createServer} from 'http';
import {execute, subscribe} from 'graphql';
import {SubscriptionServer} from 'subscriptions-transport-ws';
import {PubSub} from 'graphql-subscriptions';
import {makeExecutableSchema} from '@graphql-tools/schema';


/**
* @typedef {Object} GraphQLConfig
Expand All @@ -14,14 +22,18 @@ import {ApolloServer, gql} from 'apollo-server';
* @param {API} api
* @param {GraphQLConfig} api.config.graphql The configuration object for the GraphQL API.
*/
export function initialize(api) {
export async function initialize(api) {
const config = api.config.graphql ?? {};
const pubSub = new PubSub();

if (config.disabled) {
api.log.info('GraphQL API is disabled');
return
}

let id = 1
let messages = []

const typeDefs = gql`
type Query {
agents: [Agent]
Expand All @@ -48,6 +60,10 @@ export function initialize(api) {
type Mutation {
sendMessage(message: String!): Message
}
type Subscription {
messageSent: Message
}
`;

const resolvers = {
Expand Down Expand Up @@ -83,27 +99,66 @@ export function initialize(api) {
return response.values()
},
messages: (parent, args, context) => {
return [
{id: 1, type: 'string', content: 'This is the first message'},
{id: 2, type: 'string', content: 'This is the second message'},
{id: 3, type: 'string', content: 'This is the third message'},
{id: 4, type: 'string', content: 'This is the fourth message'},
{id: 5, type: 'string', content: 'This is the fifth message'},
]
return messages
},
},
Mutation: {
sendMessage: (parent, args, context) => {
api.log.trace('GraphQL Received Message:', args)
return {id: 1, type: 'string', content: 'A message was sent: ' + args.message ?? ''}
const message = {id: id++, type: 'string', content: args.message ?? ''}
messages.push(message)
pubSub.publish('MESSAGE_SENT', {messageSent: message})
return message
},
},
Subscription: {
messageSent: {
subscribe: () => pubSub.asyncIterator(['MESSAGE_SENT']),
},
},
};

const server = new ApolloServer({typeDefs, resolvers, context: {api}});
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});

const app = express();

app.use(cors());

const apolloServer = new ApolloServer({
schema,
context: {api, pubsub: pubSub}, // Pass the PubSub instance to the context
});

const port = config.port ?? 4000
server.listen(port).then(({url}) => {
api.log.info(`GraphQL API ready at`, url);

const httpServer = createServer(app);

await apolloServer.start()
apolloServer.applyMiddleware({app, path: '/graphql'});

httpServer.listen(port, () => {
console.log(`GraphQL Server ready at http://localhost:${port}${apolloServer.graphqlPath}`);
console.log(`GraphQL Subscriptions ready at ws://localhost:${port}${apolloServer.graphqlPath}`);
});

SubscriptionServer.create({
execute,
subscribe,
schema,
}, {
server: httpServer,
path: '/graphql',
});

let randomId = 1;
setInterval(() => {
const message = {id: id++, type: 'string', content: `Random message ${randomId++}`};
messages.push(message);
console.log('Publishing message:', message);
pubSub.publish('MESSAGE_SENT', {messageSent: message});
}, 5000);
}

Loading

0 comments on commit 254cad6

Please sign in to comment.