Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a .graphql file using `apollo-server`?

I am currently loading the GraphQL schema using a separate .graphql file, but it is encapsulated within strings:

schema.graphql

const schema = `
  type CourseType {
    _id: String!
    name: String!
  }

  type Query {
    courseType(_id: String): CourseType
    courseTypes: [CourseType]!
  }
`

module.exports = schema

Then using it for the apollo-server:

index.js

const { ApolloServer, makeExecutableSchema } = require('apollo-server')
const typeDefs = require('./schema.graphql')

const resolvers = { ... }

const schema = makeExecutableSchema({
  typeDefs: typeDefs,
  resolvers
})

const server = new ApolloServer({
  schema: schema
})

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}.`)
})

Is there any way to simply load a .graphql that looks as such? schema.graphql

type CourseType {
  _id: String!
  name: String!
}

type Query {
  courseType(_id: String): CourseType
  courseTypes: [CourseType]!
}

Then it would be parsed in the index.js? I noticed that graphql-yoga supports this, but was wondering if apollo-server does. I cannot find it anywhere in the docs. I can't get fs.readFile to work either.

like image 254
Sam Sverko Avatar asked Jun 09 '20 19:06

Sam Sverko


People also ask

How do I upload files to Apollo server?

When configuring your file upload client, you will need to send a non-empty Apollo-Require-Preflight header or Apollo Server will block the request. For example, if you use the apollo-upload-client package with Apollo Client Web, pass headers: {'Apollo-Require-Preflight': 'true'} to createUploadLink .

What is .GraphQL file?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.


3 Answers

If you define your type definitions inside a .graphql file, you can read it in one of several ways:

1.) Read the file yourself:

const { readFileSync } = require('fs')

// we must convert the file Buffer to a UTF-8 string
const typeDefs = readFileSync(require.resolve('./type-defs.graphql')).toString('utf-8')

2.) Utilize a library like graphql-tools to do it for you:

const { loadDocuments } = require('@graphql-tools/load');
const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader');

// this can also be a glob pattern to match multiple files!
const typeDefs = await loadDocuments('./type-defs.graphql', { 
    file, 
    loaders: [
        new GraphQLFileLoader()
    ]
})

3.) Use a babel plugin or a webpack loader

import typeDefs from './type-defs.graphql'
like image 137
Daniel Rearden Avatar answered Oct 16 '22 08:10

Daniel Rearden


Back in the day I wrote a teeny-tiny .graphql loader myself. It is very small, very simple, and the only thing you have to do is import it before you try to import any .graphql files. I have used it ever since even though I am sure that there are some 3rd party loaders available. Here's the code:

// graphql-loader.js

const oldJSHook = require.extensions[".js"];

const loader = (module, filename) => {
  const oldJSCompile = module._compile;
  module._compile = function (code, file) {
    code = `module.exports = \`\r${code}\`;`;
    module._compile = oldJSCompile;
    module._compile(code, file);
  };
  oldJSHook(module, filename);
};

require.extensions[".graphql"] = loader;
require.extensions[".gql"] = loader;

And then in your app:

// index.js

import "./graphql-loader"; // (or require("./graphql-loader") if you prefer)

That's it, you can then import typeDefs from "./type-defs.graphql" wherever you want.

The loader works by wrapping the text in your .graphql file inside a template string and compiling it as a simple JS module:

module.exports = ` ...your gql schema... `;
like image 2
Avius Avatar answered Oct 16 '22 07:10

Avius


This worked for me:

const { gql } = require('apollo-server');
const fs = require('fs');
const path = require('path');

//function that imports .graphql files
const importGraphQL = (file) =>{
  return fs.readFileSync(path.join(__dirname, file),"utf-8");
}

const gqlWrapper = (...files)=>{
  return gql`${files}`;
}


const enums = importGraphQL('./enums.graphql');
const schema = importGraphQL('./schema.graphql');

module.exports = gqlWrapper(enums,schema);

like image 1
Nzaki Codes Avatar answered Oct 16 '22 08:10

Nzaki Codes