Apollo-server: Apollo Server 2.0 RC and typeDefs from external file

Created on 19 Jun 2018  路  5Comments  路  Source: apollographql/apollo-server

Hello,

I'm currently migrating my Apollo server to v2.0 and I'm encounter an issue when trying to import typeDefs from another file.
Following the documentation (https://www.apollographql.com/docs/apollo-server/v2/migration-two-dot.html#gql-tag), it seems I need to write:

const typeDefs = gql${IMPORT_FUNCTION('./schema-file')};
or
const typeDefs = gql(IMPORT_FUNCTION('./schema-file'))

But it doesn't work, it seems to not recognize the IMPORT_FUNCTION.
Is the syntax correct? or IMPORT_FUNCTION should be replaced by something else? What should be the content of the schema_file to work correctly?

Maybe the documentation should be clearer on this point.
Thanks.

St茅phane

Most helpful comment

Is it possible to declare types in different files (like models) for better modularity? Like...

book.js

type Book {
    title: String
    author: String
  }

author.js

type Author {
    name: String
    dob: String
  }

All 5 comments

Totally, the documentation could use some work. Import function isn't the best example. https://github.com/apollographql/apollo-server/pull/1210 will include the doc additions. You can check it out for now to see a code snippet

Thanks @evans :smiley:

@stephanerotureau We've updated the docs and fixed the typeDefs. Thank you for flagging the issue!

Is it possible to declare types in different files (like models) for better modularity? Like...

book.js

type Book {
    title: String
    author: String
  }

author.js

type Author {
    name: String
    dob: String
  }

@BRoy98 glob.sync + fs.readFileSync + Array.prototype.reduce would do the trick.

  • glob gives you all the files that matches a pattern like *.graphql or ./**/*.gql.
  • Read those files regularly using readFile[Sync]
  • You still end up with a list of type definition strings, but reduce them to a single just but concatenation.

Pseudo-code, I haven't tested it, just writing it while I write the comment:

const typeDefs = gql`${glob.sync(__dirname.concat('*.graphql'))
  .map(filename => fs.readFileSync(filename, 'utf8))
  .reduce((typeDefs, typeDef) => `${typeDefs}\n${typeDef}`, '# My Awesome SDL')}`

Not sure if special chars like \n works with template strings and you should tweak glob pattern to your file structure.

Was this page helpful?
0 / 5 - 0 ratings