const { loadDocuments } = require('@graphql-tools/load')const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader')const { CodeFileLoader } = require('@graphql-tools/code-file-loader')// Load from stringconst document1 = loadDocuments('query { f }', { loaders: [] })// Load from a single fileconst document2 = loadDocuments('./users.query.graphql', { loaders: [new GraphQLFileLoader()] })// Load from multiple files using globconst document3 = loadDocuments('./src/**/*.graphql', { loaders: [new GraphQLFileLoader()] })// Load from code fileconst document4 = loadDocuments('./src/my-component.ts', { loaders: [new CodeFileLoader()] })
loadDocuments returns an array of document sources. Each source object has the following
structure:
interface DocumentSource { document: DocumentNode // Object representation of GraphQL Content rawSDL: string // SDL in text location: string // Way to access to that source}
loadDocuments takes in additional configuration via the options object (the second argument).
There are some defaults to be aware of - to learn more, see
the full API documentation.
Error Handling
No Files Found
In case no documents were found and loaded via the provided glob an exception is thrown.
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'import { loadDocuments } from '@graphql-tools/load'const documents = await loadDocuments(['i-do-not-exist.graphql'], { loaders: [new GraphQLFileLoader()]})
If i-do-not-exist.graphql does not exist this throws the following error:
Error: Unable to find any GraphQL type definitions for the following pointers: - *.graphql
Syntax Error within a File
In case you try to load a GraphQL file with invalid syntax, the loadDocuments function will throw
a GraphQLError.
You can identify the exact file that caused this GraphQLError by using the errors source property.
import { GraphQLError } from 'graphql'import { CodeFileLoader } from '@graphql-tools/code-file-loader'import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'import { loadDocuments } from '@graphql-tools/load'try { const documents = await loadDocuments(['packages/**/*.graphql', 'packages/**/*.ts(x)'], { loaders: [new GraphQLFileLoader(), new CodeFileLoader()] }) console.log(documents)} catch (error) { if (error instanceof GraphQLError) { console.log(error.message + `\n in ${error.source?.name}`) } throw error}
This site uses cookies for analytics and improving your experience.