Convert Figma logo to code with AI

mercurius-js logomercurius

Implement GraphQL servers and gateways with Fastify

2,430
245
2,430
63

Top Related Projects

A reference implementation of GraphQL for JavaScript

🌍  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.

Awesome list of GraphQL

🧘 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.

3,410

Code-First, Type-Safe, GraphQL Schema Construction

Quick Overview

Mercurius is a GraphQL server implementation for the Fastify web framework. It provides a simple and efficient way to build GraphQL APIs using the Fastify ecosystem, which includes features like middleware, plugins, and a robust type system.

Pros

  • Integrates with Fastify: Mercurius seamlessly integrates with the Fastify web framework, allowing developers to leverage Fastify's features and ecosystem.
  • Efficient and Performant: Mercurius is designed to be efficient and performant, with a focus on minimizing overhead and maximizing throughput.
  • Flexible and Extensible: Mercurius is highly flexible and extensible, with support for custom resolvers, directives, and plugins.
  • Robust Type System: Mercurius uses a robust type system, which helps to ensure the correctness and consistency of your GraphQL API.

Cons

  • Fastify-Specific: Mercurius is tightly coupled with the Fastify web framework, which may not be suitable for developers who prefer to use other web frameworks.
  • Learning Curve: Developers who are new to both Fastify and GraphQL may face a steeper learning curve when working with Mercurius.
  • Limited Documentation: The documentation for Mercurius, while generally good, could be more comprehensive and easier to navigate.
  • Smaller Community: Compared to some other GraphQL server implementations, Mercurius has a smaller community of users and contributors, which may limit the availability of third-party plugins and resources.

Code Examples

Here are a few examples of how to use Mercurius in a Fastify application:

  1. Setting up a basic GraphQL server:
const fastify = require('fastify');
const mercurius = require('mercurius');

const app = fastify();

app.register(mercurius, {
  schema: `
    type Query {
      hello: String!
    }
  `,
  resolvers: {
    Query: {
      hello: () => 'Hello, world!'
    }
  }
});

app.listen(3000, (err) => {
  if (err) throw err;
  console.log('Server listening on http://localhost:3000/graphql');
});
  1. Defining custom resolvers and directives:
const resolvers = {
  Query: {
    users: (_, args, context) => {
      // Fetch users from a database or other data source
      return [
        { id: 1, name: 'John Doe' },
        { id: 2, name: 'Jane Smith' }
      ];
    }
  },
  User: {
    posts: (user, args, context) => {
      // Fetch posts for the given user
      return [
        { id: 1, title: 'My First Post', userId: user.id },
        { id: 2, title: 'Another Post', userId: user.id }
      ];
    }
  }
};

const directiveResolvers = {
  uppercase: (_, { value }, { info }) => {
    return value.toUpperCase();
  }
};

app.register(mercurius, {
  schema: `
    directive @uppercase on FIELD_DEFINITION
    type User {
      id: ID!
      name: String!
      posts: [Post!]!
    }
    type Post {
      id: ID!
      title: String! @uppercase
    }
    type Query {
      users: [User!]!
    }
  `,
  resolvers,
  directiveResolvers
});
  1. Handling mutations and subscriptions:
const resolvers = {
  Query: {
    // ...
  },
  Mutation: {
    createPost: (_, { input }, context) => {
      // Create a new post and return it
      return { id: 3, title: input.title };
    }
  },
  Subscription: {
    postCreated: {
      subscribe: (_, __, { pubsub }) => {
        return pubsub.subscribe('POST_CREATED');
      },
      resolve: (

Competitor Comparisons

A reference implementation of GraphQL for JavaScript

Pros of graphql-js

  • More mature and widely adopted in the GraphQL ecosystem
  • Provides a comprehensive set of tools for building GraphQL schemas and executing queries
  • Offers greater flexibility and customization options for complex GraphQL implementations

Cons of graphql-js

  • Steeper learning curve, especially for developers new to GraphQL
  • Requires more boilerplate code to set up a GraphQL server
  • Performance may be slower compared to Mercurius for high-load scenarios

Code Comparison

graphql-js:

const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');

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

Mercurius:

const fastify = require('fastify')();

fastify.register(require('mercurius'), {
  schema: `
    type Query {
      hello: String
    }
  `,
  resolvers: {
    Query: {
      hello: () => 'Hello, World!'
    }
  }
});

This comparison highlights the more concise setup process in Mercurius, which integrates seamlessly with Fastify, while graphql-js requires more manual configuration but offers greater flexibility for complex schemas.

🌍  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

  • More extensive ecosystem with additional tools and integrations
  • Larger community and wider adoption, leading to more resources and support
  • Advanced features like federation and gateway for microservices architecture

Cons of Apollo Server

  • Heavier and more complex, potentially impacting performance
  • Steeper learning curve for beginners
  • Less focus on specific Node.js frameworks like Fastify

Code Comparison

Apollo Server:

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

Mercurius:

const Fastify = require('fastify');
const mercurius = require('mercurius');
const app = Fastify();
app.register(mercurius, { schema, resolvers });
app.listen(3000);

Key Differences

  • Mercurius is specifically designed for Fastify, while Apollo Server is framework-agnostic
  • Apollo Server offers a more comprehensive set of features out of the box
  • Mercurius focuses on performance and simplicity within the Fastify ecosystem
  • Apollo Server has better support for complex GraphQL setups and distributed systems
  • Mercurius leverages Fastify's plugin system for extensibility

Both projects aim to provide GraphQL server functionality, but they cater to different use cases and preferences. Apollo Server is more suitable for large-scale applications with complex requirements, while Mercurius excels in Fastify-based projects prioritizing performance and simplicity.

Awesome list of GraphQL

Pros of awesome-graphql

  • Comprehensive resource collection for GraphQL, covering various aspects and tools
  • Regularly updated with community contributions, ensuring up-to-date information
  • Provides a wide range of resources for learning, implementing, and exploring GraphQL

Cons of awesome-graphql

  • Not a functional library or tool, but rather a curated list of resources
  • May require additional effort to find specific implementation details or code examples
  • Can be overwhelming for beginners due to the vast amount of information

Code comparison

As awesome-graphql is a curated list and not a functional library, a direct code comparison is not applicable. However, here's an example of how Mercurius can be used to set up a GraphQL server:

const Fastify = require('fastify')
const mercurius = require('mercurius')

const app = Fastify()
app.register(mercurius, {
  schema: schema,
  resolvers: resolvers
})

awesome-graphql would typically include links to various GraphQL implementations and tools, rather than providing code snippets directly.

🧘 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

  • More flexible and framework-agnostic, supporting various HTTP servers and environments
  • Extensive plugin system for easy customization and feature extension
  • Built-in support for GraphQL subscriptions and file uploads

Cons of GraphQL Yoga

  • Potentially higher learning curve due to its flexibility and extensive features
  • May require more configuration for optimal performance in specific use cases
  • Slightly larger bundle size compared to Mercurius

Code Comparison

Mercurius:

const fastify = require('fastify')()
const mercurius = require('mercurius')

fastify.register(mercurius, {
  schema: schema,
  resolvers: resolvers
})

GraphQL Yoga:

import { createServer } from 'node:http'
import { createYoga } from 'graphql-yoga'

const yoga = createYoga({ schema })
const server = createServer(yoga)
server.listen(4000, () => {
  console.log('Server is running on http://localhost:4000/graphql')
})

Both Mercurius and GraphQL Yoga are powerful GraphQL server implementations, but they cater to different needs. Mercurius is tightly integrated with Fastify, offering excellent performance for Fastify-based applications. GraphQL Yoga, on the other hand, provides more flexibility and can be used with various HTTP servers and frameworks. The choice between the two depends on the specific requirements of your project and your preferred development ecosystem.

3,410

Code-First, Type-Safe, GraphQL Schema Construction

Pros of Nexus

  • Strong TypeScript support with auto-generated types
  • Declarative schema definition with code-first approach
  • Rich plugin ecosystem for extending functionality

Cons of Nexus

  • Steeper learning curve for developers new to code-first GraphQL
  • Less performant for high-load scenarios compared to Mercurius
  • Requires more setup and configuration for basic functionality

Code Comparison

Nexus schema definition:

const Query = objectType({
  name: 'Query',
  definition(t) {
    t.list.field('users', {
      type: 'User',
      resolve: () => fetchUsers(),
    })
  },
})

Mercurius schema definition:

type Query {
  users: [User]
}

Mercurius resolver:

const resolvers = {
  Query: {
    users: async () => fetchUsers()
  }
}

Nexus focuses on a code-first approach with TypeScript, offering strong type safety and auto-generated types. It provides a more declarative way to define schemas but requires more setup.

Mercurius uses a schema-first approach, separating schema definition from resolvers. It's generally easier to get started with and offers better performance for high-load scenarios, but lacks some of the advanced TypeScript features of Nexus.

Both libraries have their strengths, and the choice depends on project requirements, team expertise, and performance needs.

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

Mercurius Logo

mercurius

CI workflow NPM version NPM downloads neostandard javascript style

Mercurius is a GraphQL adapter for Fastify

Features:

  • Caching of query parsing and validation.
  • Automatic loader integration to avoid 1 + N queries.
  • Just-In-Time compiler via graphql-jit.
  • Subscriptions.
  • Federation support via @mercuriusjs/federation, including Subscriptions.
  • Gateway implementation via @mercuriusjs/gateway, including Subscriptions.
  • Batched query support.
  • Customisable persisted queries.

Docs

Install

npm i fastify mercurius graphql
# or
yarn add fastify mercurius graphql

The previous name of this module was fastify-gql (< 6.0.0).

Quick Start

'use strict'

const Fastify = require('fastify')
const mercurius = require('mercurius')

const app = Fastify()

const schema = `
  type Query {
    add(x: Int, y: Int): Int
  }
`

const resolvers = {
  Query: {
    add: async (_, { x, y }) => x + y
  }
}

app.register(mercurius, {
  schema,
  resolvers
})

app.get('/', async function (req, reply) {
  const query = '{ add(x: 2, y: 2) }'
  return reply.graphql(query)
})

app.listen({ port: 3000 })

Examples

Check GitHub repo for more examples.

Acknowledgements

The project is kindly sponsored by:

The Mercurius name was gracefully donated by Marco Castelluccio. The usage of that library was described in https://hacks.mozilla.org/2015/12/web-push-notifications-from-irssi/, and you can find that codebase in https://github.com/marco-c/mercurius.

License

MIT

NPM DownloadsLast 30 Days