Express-graphql: Refresh schema on runtime

Created on 21 Oct 2018  路  3Comments  路  Source: graphql/express-graphql

We give users the ability to define data model and generate GQL schema on the run, so how do I refresh the schema when there is new model added?

question

Most helpful comment

@naivefun Instead of options you can pass callback that return options:

app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({
  schema: MyGraphQLSchema,
  rootValue: await someFunctionToGetRootValue(request),
  graphiql: true
})));

All 3 comments

After some research I find out that the schema seems just a reference to options.schema, maybe I can simply update options to achieve what I need. TBT.

@naivefun Instead of options you can pass callback that return options:

app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({
  schema: MyGraphQLSchema,
  rootValue: await someFunctionToGetRootValue(request),
  graphiql: true
})));

I have the same question, but a little different in details:
For example:
If I store types in DB, sth like:

Types: [
  { name: "test", type: "string" }, 
  { name: "score", type: "float" }
]

Whenever server starts or someone called APIs that change Types data in DB, it triggers updateTypes():

let fields = { name: "default", type: GraphQLString };
updateTypes() {
  fields = await getTypesFromDB() // then convert fields to { ${name}: { type: GraphQL${type}, ... }
  const TestType = new GraphQLObjectType({
    name: 'TestType',
    fields: () => ({ ...fields })
  })
  module.exports = TestType
} 

The exported value gets updated, but in app.js:

import schema from './schema'
app.use('/graphql', graphqlHTTP({
  schema: schema
  ...
))

It's still using the old schema. Is there anyway to make schema use the updated value?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stevvvn picture stevvvn  路  3Comments

PavanBahuguni picture PavanBahuguni  路  3Comments

KieronWiltshire picture KieronWiltshire  路  3Comments

m-diiorio picture m-diiorio  路  4Comments

kaareal picture kaareal  路  3Comments