Getting Started with GraphQL using graphql‑js: Schema, Queries, and Tooling

This article introduces GraphQL as a query language for APIs, explains its history, shows how to define a schema and resolvers with graphql‑js, demonstrates query execution, error handling, built‑in types, and presents useful development tools such as GraphiQL and graphql‑import.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Getting Started with GraphQL using graphql‑js: Schema, Queries, and Tooling

GraphQL is a query language and execution engine for APIs, originally created by Facebook in 2013 and standardized as an open specification in 2015. It enables clients to request exactly the data they need, reducing over‑fetching and under‑fetching.

The official GraphQL ecosystem provides implementations in 12 languages; graphql‑js is the JavaScript reference implementation and the basis of the examples in this guide.

Basic knowledge

The GraphQL service processes requests by combining a server‑side schema, a root value (resolver map), and a client‑side query string. The schema defines the types and entry points, while resolvers provide the actual data.

Below is a minimal example that builds a schema, defines a resolver, and executes a query using graphql:

import { graphql, buildSchema } from 'graphql';

const schemaText = `
    type Query {
        fruits: [Fruit]
    }
    type Fruit {
        id: ID!
        name: String
    }
`;

const schema = buildSchema(schemaText);

const query = `
    query fruits {
        fruits {
            id
            name
        }
    }
`;

const rootValue = {
    fruits: () => [
        { id: 'ZnJ1aXQ', name: 'apple' },
        { id: 'YmFubmF', name: 'cherry' }
    ]
};

graphql(schema, query, rootValue).then(ret => console.log(ret));

The execution returns a Promise<GraphQLResult> whose resolved value contains a data field with the requested fields, or an errors array if validation or resolver errors occur.

Schema definition

The schema is written in the GraphQL Schema Language. It consists of type definitions such as type Query, custom object types (e.g., type Fruit), and optional modifiers like ! for non‑null and [] for lists. Built‑in scalar types include String, Int, Float, Boolean, and ID. Additional type kinds are enum, interface, union, and input.

Root value and resolvers

The rootValue object maps each field in the Query (or Mutation) type to a resolver function. When a client sends a query, GraphQL invokes the matching resolver and returns its result. Resolvers can be synchronous or asynchronous; any thrown error or rejected promise is captured and placed in the errors array.

Error handling

If a client queries a field that does not exist in the schema, GraphQL returns an error object with location information, e.g.,

{"message":"Cannot query field \"meats\" on type \"Query\".","locations":[{"line":2,"column":5}]}

. All validation and runtime errors follow this structure.

Development tools

Two commonly used tools are highlighted:

GraphiQL : an in‑browser IDE that provides schema‑aware autocomplete, query building, and result inspection.

graphql‑import : a utility that enables modular schema composition by allowing # import statements in .graphql files and merging them into a single schema string.

Using graphql‑import, you can split large schemas into feature‑specific files and combine them at build time:

import { importSchema } from 'graphql-import';
const schemaString = importSchema('index.graphql');

When merging, duplicate type definitions are overridden, so naming conventions (e.g., module prefixes) should be used to avoid conflicts.

Summary

The guide walks through the essential steps to set up a GraphQL server with graphql‑js, explains schema design, query execution, error handling, and introduces tooling that streamlines development. With this foundation, developers can explore advanced features such as variables, directives, and custom scalars.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptAPITutorialschemaGraphQL
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.