GraphQL.js
Builds schemas and executes GraphQL operations as the reference JavaScript runtime.
- Downloads / mo
- 270.5M
- Stars
- 20.3K
- Last release
- 17.1.0
- License
- MIT
Strengths
- Validates queries before execution. The graphql function validates the query before running its resolvers.
- Builds schemas directly in code. Define object types and field resolvers with the schema constructors.
Limitations
- Subscriptions need a transport layer. Connect subscription execution to an event system and network transport.
- Custom pipelines need validation. Run operation validation separately when building a low-level execution pipeline.
Quickstart
import { buildSchema, graphql } from 'graphql'; const schema = buildSchema('type Query { hello: String }'); const result = await graphql({ schema, source: '{ hello }', rootValue: { hello: () => 'world' } });
GraphQL.js examples
export function makeContextQueryFn( schema: GraphQLSchema, operation: 'query' | 'mutation', field: GraphQLField<any, unknown> ) { const { argumentNodes, variableDefinitions } = getVariablesForGraphQLField(field) const rootName = getRootTypeName(field.type) const exec = async (args: Record<string, any>, query: string, context: KeystoneContext) => { const selectionSet = ( parse(`fragment x on ${rootName} {${query}}`).definitions[0] as FragmentDefinitionNode ).selectionSet const document: DocumentNode = { kind: Kind.DOCUMENT, definitions: [ { kind: Kind.OPERATION_DEFINITION, // OperationTypeNode is an ts enum where the values are 'query' | 'mutation' | 'subscription' operation: operation as OperationTypeNode, selectionSet: { kind: Kind.SELECTION_SET, selections: [ { kind: Kind.FIELD, name: { kind: Kind.NAME, value: field.name }, arguments: argumentNodes, selectionSet: selectionSet, }, ], }, variableDefinitions, }, ], } const validationErrors = validate(schema, document) if (validationErrors.length > 0) { throw validationErrors[0] } const result = await execute({ schema, document, contextValue: context, variableValues: Object.fromEntries( // GraphQL for some reason decides to make undefined values in args // skip defaulting for some reason // this ofc doesn't technically fully fix it (bc nested things) // but for the cases where we care, it does Object.entries(args).filter(([, val]) => val !== undefined) ), rootValue: {}, }) if (result.errors?.length) { throw result.errors[0] } return result.data![field.name] } return ( _args: { query?: string } & Record<string, unknown> = {}, // WARNING: sometimes this is undefined somewhere context: KeystoneContext ) => { const { query, ...args } = _args return exec(args, query ?? 'id', context) as Promise<any> } }