Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQLJS use a .graphql file for a query from nodejs

I have created a basic GraphQL Express app and I'm wanting to bundle pre defined data from pre defined queries with specific routes.

Ideally the query should allow providing arguments so it can be used flexibly, I would like to be able to save the query to a file and run it on demand but provide arguments specific to the current data required.

I can query the api with the following query

query authors(ids: [1337, 42]) {
  name,
  id
}

The query.graphql file should be something like the following:

getAuthorsById($ids: Int[]) {
  authors(ids: $ids) {
    name,
    id
  }
}

What I want to do within the Node server is get the content from a query.graphql file and execute it when a specific route is fired eg.

const query = somehowImportTheQuery('./query.graphql')
graphql(schema, query([1337, 42]))

The above code somehowImportTheQuery should import the query and return a function getAuthorsById that can be called with arguments.

Does something like this already exist? or are there any tools or documentation that can help me achieve the desired functionality?

Thanks for any help!

like image 769
synthet1c Avatar asked Dec 28 '25 04:12

synthet1c


1 Answers

You could use documents-loading of graphql-tools module to load GraphQL operation documents from different sources.

E.g.

index.ts:

import { GraphQLSchema, buildSchema, graphql } from 'graphql';
import { loadDocumentsSync, GraphQLFileLoader } from 'graphql-tools';
import path from 'path';

const typeDefs: string = `
    type Author {
        id: ID!
        name: String
    }
    type Query {
        authors(ids: [ID]!): [Author]!
    }
`;
const resolvers = {
  authors({ ids }) {
    return [
      { id: ids[0], name: 'a' },
      { id: ids[1], name: 'b' },
    ];
  },
};

const schema: GraphQLSchema = buildSchema(typeDefs);

const query = loadDocumentsSync(path.resolve(__dirname, './query.graphql'), {
  loaders: [new GraphQLFileLoader()],
});

graphql({
  schema,
  source: query[0].rawSDL!,
  rootValue: resolvers,
  variableValues: { ids: [1337, 42] },
}).then(({ data }) => {
  console.log(data);
});

query.graphql:

query getAuthorsById($ids: [ID]!) {
  authors(ids: $ids) {
    name
    id
  }
}

The execution result:

[Object: null prototype] {
  authors:
   [ [Object: null prototype] { name: 'a', id: '1337' },
     [Object: null prototype] { name: 'b', id: '42' } ] }
like image 143
slideshowp2 Avatar answered Dec 30 '25 22:12

slideshowp2