graphql / express-graphql

Create a GraphQL HTTP server with Express.
MIT License
6.34k stars 538 forks source link

Update GraphQL Schema at runtime #791

Open johanlelan opened 2 years ago

johanlelan commented 2 years ago

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 ?

JaLe29 commented 2 years ago
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');
johanlelan commented 2 years ago

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...

JaLe29 commented 2 years ago

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

enisdenjo commented 1 year ago

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!