Convert Figma logo to code with AI

graphql logographql-js

A reference implementation of GraphQL for JavaScript

20,023
2,018
20,023
275

Top Related Projects

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.

9,867

An implementation of GraphQL for Go / Golang

Awesome list of GraphQL

GraphQL is a query language and execution engine tied to any backend service.

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Quick Overview

GraphQL.js is the JavaScript reference implementation for GraphQL, a query language for APIs. It provides a robust set of tools for building GraphQL schemas and executing queries against those schemas. This library is maintained by the GraphQL Foundation and is widely used in both server-side and client-side applications.

Pros

  • Flexible and powerful schema definition system
  • Excellent TypeScript support
  • Comprehensive validation and error handling
  • Well-documented and actively maintained

Cons

  • Steeper learning curve compared to REST APIs
  • Can be overkill for simple APIs
  • Performance considerations for complex queries
  • Requires careful design to avoid N+1 query problems

Code Examples

  1. Defining a simple GraphQL schema:
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'Hello, world!';
        },
      },
    },
  }),
});
  1. Executing a query:
const { graphql } = require('graphql');

const query = '{ hello }';

graphql(schema, query).then((result) => {
  console.log(result);
});
  1. Using GraphQL with Express:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));

app.listen(4000);

Getting Started

To start using GraphQL.js in your project:

  1. Install the package:

    npm install graphql
    
  2. Create a schema and define types:

    const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');
    
    const schema = new GraphQLSchema({
      query: new GraphQLObjectType({
        name: 'RootQueryType',
        fields: {
          hello: {
            type: GraphQLString,
            resolve() {
              return 'Hello, GraphQL!';
            },
          },
        },
      }),
    });
    
  3. Execute a query:

    const { graphql } = require('graphql');
    
    graphql(schema, '{ hello }').then((result) => {
      console.log(result);
    });
    

This basic setup allows you to start exploring GraphQL.js functionality. For more advanced usage, refer to the official documentation.

Competitor Comparisons

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

Pros of Apollo Server

  • Provides a complete, production-ready GraphQL server solution
  • Offers built-in features like caching, subscriptions, and schema stitching
  • Extensive ecosystem with tools for testing, monitoring, and client integration

Cons of Apollo Server

  • Higher learning curve due to more complex architecture
  • Potentially overkill for simple GraphQL implementations
  • Opinionated approach may limit flexibility in certain scenarios

Code Comparison

GraphQL.js (basic setup):

const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = { hello: () => 'Hello world!' };

graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

Apollo Server (basic setup):

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Both GraphQL.js and Apollo Server are popular choices for implementing GraphQL in JavaScript. GraphQL.js is the reference implementation and offers a lightweight, flexible approach. Apollo Server builds on top of GraphQL.js, providing a more comprehensive solution with additional features and tooling, but at the cost of increased complexity.

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.

Pros of GraphQL Yoga

  • Simplified setup and configuration for GraphQL servers
  • Built-in support for subscriptions and file uploads
  • Integrates well with various frameworks and environments

Cons of GraphQL Yoga

  • Less flexible for advanced customization compared to GraphQL.js
  • May have a steeper learning curve for developers new to GraphQL
  • Potentially larger bundle size due to additional features

Code Comparison

GraphQL.js:

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = { hello: () => 'Hello world!' };

const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);

GraphQL Yoga:

import { createServer } from '@graphql-yoga/node'

const server = createServer({
  schema: {
    typeDefs: `
      type Query {
        hello: String
      }
    `,
    resolvers: {
      Query: {
        hello: () => 'Hello world!'
      }
    }
  }
})

server.start()
9,867

An implementation of GraphQL for Go / Golang

Pros of graphql-go

  • Native Go implementation, offering better performance and integration with Go ecosystems
  • Lightweight and minimalistic design, suitable for smaller projects or microservices
  • Easier to learn and use for Go developers already familiar with the language

Cons of graphql-go

  • Less mature and feature-rich compared to graphql-js
  • Smaller community and ecosystem, resulting in fewer third-party tools and extensions
  • May require more manual implementation of certain GraphQL features

Code Comparison

graphql-js (JavaScript):

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'Hello, world!';
        },
      },
    },
  }),
});

graphql-go (Go):

var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query: graphql.NewObject(graphql.ObjectConfig{
        Name: "RootQuery",
        Fields: graphql.Fields{
            "hello": &graphql.Field{
                Type: graphql.String,
                Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                    return "Hello, world!", nil
                },
            },
        },
    }),
})

Both repositories provide implementations of the GraphQL specification in their respective languages. graphql-js is more established and feature-complete, while graphql-go offers native Go performance and integration. The choice between them depends on the project requirements, team expertise, and ecosystem preferences.

Awesome list of GraphQL

Pros of awesome-graphql

  • Comprehensive collection of GraphQL resources, tools, and libraries
  • Regularly updated with community contributions
  • Covers a wide range of GraphQL-related topics and ecosystems

Cons of awesome-graphql

  • Not a functional library or implementation of GraphQL
  • May include outdated or less maintained resources
  • Requires additional effort to evaluate and choose appropriate tools

Code comparison

While a direct code comparison isn't relevant due to the nature of these repositories, here's a brief example of how they differ:

awesome-graphql (README.md):

## Tools
- [GraphiQL](https://github.com/graphql/graphiql) - An in-browser IDE for exploring GraphQL.
- [GraphQL Playground](https://github.com/prisma/graphql-playground) - GraphQL IDE for better development workflows.

graphql-js (src/index.js):

export {
  // Core GraphQL library
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLInputObjectType,
  // ... other exports
} from './graphql';

awesome-graphql serves as a curated list of GraphQL resources, while graphql-js is the reference implementation of GraphQL in JavaScript. The former helps developers discover tools and libraries, while the latter provides the core functionality for building GraphQL servers and clients in JavaScript environments.

GraphQL is a query language and execution engine tied to any backend service.

Pros of graphql-spec

  • Provides the official specification for GraphQL, serving as the authoritative reference
  • Language-agnostic, allowing developers to implement GraphQL in various programming languages
  • Offers detailed explanations of GraphQL concepts and behaviors

Cons of graphql-spec

  • Not directly executable or usable in projects; requires implementation
  • May be more challenging for beginners to understand without practical examples
  • Updates to the spec can be slower compared to implementation-specific repositories

Code Comparison

graphql-spec (example schema definition):

type Query {
  hero: Character
}

interface Character {
  id: ID!
  name: String!
  friends: [Character]
}

graphql-js (example usage):

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      hero: { type: CharacterInterface }
    }
  })
});

Summary

graphql-spec is the official specification for GraphQL, providing a comprehensive and language-agnostic reference. It's essential for understanding GraphQL's core concepts and behaviors but requires implementation in specific languages.

graphql-js, on the other hand, is a JavaScript implementation of GraphQL, offering a practical, ready-to-use solution for Node.js developers. It provides a more hands-on approach with executable code and examples, making it easier for developers to integrate GraphQL into their projects quickly.

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Pros of GraphQL Engine

  • Provides a complete, ready-to-use GraphQL server with built-in authorization and database integration
  • Offers real-time subscriptions out of the box
  • Includes a user-friendly web interface for schema management and API exploration

Cons of GraphQL Engine

  • Less flexible for custom GraphQL implementations compared to GraphQL.js
  • Steeper learning curve for developers new to Hasura's ecosystem
  • More opinionated architecture, which may not suit all project requirements

Code Comparison

GraphQL.js:

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'Hello, World!';
        },
      },
    },
  }),
});

GraphQL Engine:

type: query
name: hello
schema:
  response: String
handler: '{{HASURA_GRAPHQL_ENGINE_HOSTNAME}}/api/rest/hello'

GraphQL.js provides a more programmatic approach to defining schemas, while GraphQL Engine uses a declarative YAML-based configuration. GraphQL.js offers greater flexibility but requires more code, whereas GraphQL Engine simplifies schema creation at the cost of some customization options.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

GraphQLConf 2024 Banner: September 10-12, San Francisco. Hosted by the GraphQL Foundation

GraphQL.js

The JavaScript reference implementation for GraphQL, a query language for APIs created by Facebook.

npm version Build Status Coverage Status

See more complete documentation at https://graphql.org/ and https://graphql.org/graphql-js/.

Looking for help? Find resources from the community.

Getting Started

A general overview of GraphQL is available in the README for the Specification for GraphQL. That overview describes a simple set of GraphQL examples that exist as tests in this repository. A good way to get started with this repository is to walk through that README and the corresponding tests in parallel.

Using GraphQL.js

Install GraphQL.js from npm

With npm:

npm install --save graphql

or using yarn:

yarn add graphql

GraphQL.js provides two important capabilities: building a type schema and serving queries against that type schema.

First, build a GraphQL type schema which maps to your codebase.

import {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';

var schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'world';
        },
      },
    },
  }),
});

This defines a simple schema, with one type and one field, that resolves to a fixed value. The resolve function can return a value, a promise, or an array of promises. A more complex example is included in the top-level tests directory.

Then, serve the result of a query against that type schema.

var source = '{ hello }';

graphql({ schema, source }).then((result) => {
  // Prints
  // {
  //   data: { hello: "world" }
  // }
  console.log(result);
});

This runs a query fetching the one field defined. The graphql function will first ensure the query is syntactically and semantically valid before executing it, reporting errors otherwise.

var source = '{ BoyHowdy }';

graphql({ schema, source }).then((result) => {
  // Prints
  // {
  //   errors: [
  //     { message: 'Cannot query field BoyHowdy on RootQueryType',
  //       locations: [ { line: 1, column: 3 } ] }
  //   ]
  // }
  console.log(result);
});

Note: Please don't forget to set NODE_ENV=production if you are running a production server. It will disable some checks that can be useful during development but will significantly improve performance.

Want to ride the bleeding edge?

The npm branch in this repository is automatically maintained to be the last commit to main to pass all tests, in the same form found on npm. It is recommended to use builds deployed to npm for many reasons, but if you want to use the latest not-yet-released version of graphql-js, you can do so by depending directly on this branch:

npm install graphql@git://github.com/graphql/graphql-js.git#npm

Experimental features

Each release of GraphQL.js will be accompanied by an experimental release containing support for the @defer and @stream directive proposal. We are hoping to get community feedback on these releases before the proposal is accepted into the GraphQL specification. You can use this experimental release of GraphQL.js by adding the following to your project's package.json file.

"graphql": "experimental-stream-defer"

Community feedback on this experimental release is much appreciated and can be provided on the issue created for this purpose.

Using in a Browser

GraphQL.js is a general-purpose library and can be used both in a Node server and in the browser. As an example, the GraphiQL tool is built with GraphQL.js!

Building a project using GraphQL.js with webpack or rollup should just work and only include the portions of the library you use. This works because GraphQL.js is distributed with both CommonJS (require()) and ESModule (import) files. Ensure that any custom build configurations look for .mjs files!

Contributing

We actively welcome pull requests. Learn how to contribute.

This repository is managed by EasyCLA. Project participants must sign the free (GraphQL Specification Membership agreement before making a contribution. You only need to do this one time, and it can be signed by individual contributors or their employers.

To initiate the signature process please open a PR against this repo. The EasyCLA bot will block the merge if we still need a membership agreement from you.

You can find detailed information here. If you have issues, please email operations@graphql.org.

If your company benefits from GraphQL and you would like to provide essential financial support for the systems and people that power our community, please also consider membership in the GraphQL Foundation.

Changelog

Changes are tracked as GitHub releases.

License

GraphQL.js is MIT-licensed.

NPM DownloadsLast 30 Days