express-graphql icon indicating copy to clipboard operation
express-graphql copied to clipboard

Update GraphQL Schema at runtime

Open johanlelan opened this issue 3 years ago • 4 comments

Hi everyone!

We need a help on Schema update. Our types are stored into DB. We want to update the GraphQL Schema on-the-fly when a type is updated.

How can we do this on express-graphql ?

johanlelan avatar Nov 24 '21 20:11 johanlelan

var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');

let iterator = 0;

var app = express(); 

var schema1 = buildSchema(`
  type Query {
    hello: String
  }
`);

var schema2 = buildSchema(`
  type Query {
    hello2: String
  }
`);

var root1 = {
	hello: () => {

		return 'hello';
	},
};

var root2 = {
	hello2: () => {
		return 'hello2';
	},
};

app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => {
	return {
		schema: iterator % 2 === 0 ? schema1 : schema2,
		rootValue: iterator % 2 === 0 ? root1 : root2,
		graphiql: true
	}
}));

setInterval(()=> {
	console.log('tick')
	iterator++; 
}, 5000)

app.listen(4001);
console.log('Running a GraphQL API server at http://localhost:4001/graphql');

JaLe29 avatar May 24 '22 19:05 JaLe29

Thanks @JaLe29! I am looking for mutate the schema1 at run time. My use case is adding query types during service life. I have a mutation to declare sources into DB. Each source will be a new graphQL type...

johanlelan avatar May 24 '22 19:05 johanlelan

So, you can make it from variable on the fly in app.use callback.

JaLe29 avatar May 24 '22 20:05 JaLe29

This library has been deprecated and this repo will be archived soon. It has been superseded by graphql-http.

Furthermore, if you seek a fully-featured, well-maintained and performant server - I heavily recommend GraphQL Yoga!

enisdenjo avatar Mar 20 '23 12:03 enisdenjo