Convert Figma logo to code with AI

graphql-nexus logonexus

Code-First, Type-Safe, GraphQL Schema Construction

3,395
274
3,395
255

Top Related Projects

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

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

A reference implementation of GraphQL for JavaScript

66,731

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Quick Overview

Nexus is a declarative, code-first, and strongly typed GraphQL schema construction library for TypeScript/JavaScript. It provides a powerful and intuitive API for building GraphQL schemas, with features like automatic TypeScript type generation and plugin system for extending functionality.

Pros

  • Strong TypeScript integration with automatic type generation
  • Declarative and intuitive API for schema definition
  • Extensible plugin system for adding custom functionality
  • Excellent developer experience with auto-completion and type safety

Cons

  • Steeper learning curve compared to SDL-first approaches
  • Requires TypeScript knowledge for optimal usage
  • May be overkill for simple GraphQL APIs
  • Documentation can be overwhelming for beginners

Code Examples

  1. Defining a simple object type:
import { objectType } from 'nexus'

const User = objectType({
  name: 'User',
  definition(t) {
    t.int('id')
    t.string('name')
    t.string('email')
  },
})
  1. Creating a query field:
import { queryField, stringArg } from 'nexus'

const hello = queryField('hello', {
  type: 'String',
  args: {
    name: stringArg(),
  },
  resolve: (_, { name }) => `Hello, ${name || 'World'}!`,
})
  1. Defining a mutation:
import { mutationField, nonNull, stringArg } from 'nexus'

const createUser = mutationField('createUser', {
  type: 'User',
  args: {
    name: nonNull(stringArg()),
    email: nonNull(stringArg()),
  },
  resolve: (_, { name, email }, ctx) => {
    // Implement user creation logic here
    return ctx.db.createUser({ name, email })
  },
})

Getting Started

  1. Install Nexus and its dependencies:
npm install nexus graphql
  1. Create a basic schema:
import { makeSchema, objectType, queryType } from 'nexus'

const User = objectType({
  name: 'User',
  definition(t) {
    t.int('id')
    t.string('name')
  },
})

const Query = queryType({
  definition(t) {
    t.list.field('users', {
      type: 'User',
      resolve: () => [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }],
    })
  },
})

export const schema = makeSchema({
  types: [User, Query],
  outputs: {
    schema: __dirname + '/schema.graphql',
    typegen: __dirname + '/generated/nexus.ts',
  },
})

This creates a simple schema with a User type and a query to fetch users. Nexus will generate the corresponding GraphQL schema and TypeScript types.

Competitor Comparisons

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • More comprehensive database toolkit with ORM capabilities
  • Supports multiple databases (PostgreSQL, MySQL, SQLite, etc.)
  • Provides database migrations and introspection

Cons of Prisma

  • Steeper learning curve due to its broader feature set
  • Less focused on GraphQL-specific functionality
  • May introduce additional complexity for simple projects

Code Comparison

Prisma schema definition:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

Nexus type definition:

objectType({
  name: 'User',
  definition(t) {
    t.int('id')
    t.string('email')
    t.string('name', { nullable: true })
    t.list.field('posts', { type: 'Post' })
  },
})

While Prisma focuses on database schema definition and ORM functionality, Nexus is specifically designed for building GraphQL schemas. Prisma provides a more comprehensive solution for database management, including migrations and multiple database support. Nexus, on the other hand, offers a more focused approach to GraphQL schema definition with type-safety and code-first development.

Prisma is better suited for projects requiring robust database management, while Nexus excels in GraphQL-specific schema development. The choice between the two depends on the project's requirements and the developer's preference for database-first or code-first approaches.

🌍  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 mature and widely adopted, with extensive documentation and community support
  • Offers a broader ecosystem of tools and integrations (Apollo Client, Apollo Studio)
  • Provides built-in features like caching, subscriptions, and file uploads

Cons of Apollo Server

  • Can be more complex to set up and configure for simple use cases
  • Less type-safe compared to Nexus, which offers stronger TypeScript integration
  • Requires more boilerplate code for schema definition

Code Comparison

Apollo Server schema definition:

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

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

Nexus schema definition:

const Query = objectType({
  name: 'Query',
  definition(t) {
    t.string('hello', {
      resolve: () => 'Hello world!',
    });
  },
});

Key Differences

  • Nexus provides a code-first approach to schema definition, while Apollo Server typically uses SDL-first
  • Nexus offers better TypeScript integration and type safety out of the box
  • Apollo Server has a larger ecosystem and more built-in features for production use
  • Nexus focuses on developer experience and type safety, while Apollo Server emphasizes flexibility and scalability

A reference implementation of GraphQL for JavaScript

Pros of graphql-js

  • More mature and widely adopted in the GraphQL ecosystem
  • Provides lower-level control and flexibility for custom implementations
  • Extensive documentation and community support

Cons of graphql-js

  • Requires more boilerplate code for schema definition
  • Steeper learning curve for beginners
  • Less opinionated, which can lead to inconsistent implementations

Code Comparison

graphql-js:

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

Nexus:

const Query = objectType({
  name: 'Query',
  definition(t) {
    t.string('hello', {
      resolve: () => 'Hello, World!'
    })
  }
});

const schema = makeSchema({
  types: [Query]
});

Summary

graphql-js is the reference implementation of GraphQL in JavaScript, offering more control and flexibility but requiring more setup. Nexus, on the other hand, provides a more declarative and type-safe approach to schema definition, making it easier for developers to build GraphQL APIs with less boilerplate. While graphql-js is more established, Nexus offers a more modern and developer-friendly experience, especially for TypeScript users.

66,731

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Pros of Nest

  • Full-featured framework with built-in support for various architectural patterns
  • Strong TypeScript integration and decorators for enhanced developer experience
  • Extensive ecosystem with modules for various functionalities (e.g., database, authentication)

Cons of Nest

  • Steeper learning curve due to its comprehensive nature
  • Potentially overkill for smaller projects or microservices
  • Less focused on GraphQL specifically compared to Nexus

Code Comparison

Nest (Controller):

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

Nexus (Schema Definition):

const Cat = objectType({
  name: 'Cat',
  definition(t) {
    t.string('name')
    t.int('age')
  },
})

Key Differences

  • Nest is a full-stack framework, while Nexus focuses on GraphQL schema definition
  • Nest uses decorators extensively, Nexus relies on function calls and objects
  • Nest provides a more opinionated structure, Nexus offers flexibility in schema design

Use Cases

  • Choose Nest for large-scale applications requiring a comprehensive framework
  • Opt for Nexus when building GraphQL-centric APIs with a focus on schema design

Community and Ecosystem

  • Nest has a larger community and more third-party modules
  • Nexus has a dedicated GraphQL-focused community and integrates well with other GraphQL tools

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

Nexus

trunk npm version

Declarative, code-first and strongly typed GraphQL schema construction for TypeScript & JavaScript.

Installation

npm install nexus graphql

Note you must also add graphql. Nexus pins to it as a peer dependency.

Features

  • Expressive, declarative API for building schemas
  • Full type-safety for free
  • Powerful plugin system
  • No need to re-declare interface fields per-object
  • Optionally possible to reference types by name (with autocomplete)
    Rather than needing to import every single piece of the schema
  • Interoperable with vanilla graphql-js types, and it's just a GraphQLSchema
    So it fits in just fine with existing community solutions of apollo-server, graphql-middleware, etc.
  • Inline function resolvers
    For when you need to do simple field aliasing
  • Auto-generated graphql SDL schema
    Great for when seeing how any code changes affected the schema
  • DRY-up schema design
    Create higher level "functions" which wrap common fields

Example

import { queryType, stringArg, makeSchema } from 'nexus'
import { GraphQLServer } from 'graphql-yoga'

const Query = queryType({
  definition(t) {
    t.string('hello', {
      args: { name: stringArg() },
      resolve: (parent, { name }) => `Hello ${name || 'World'}!`,
    })
  },
})

const schema = makeSchema({
  types: [Query],
  outputs: {
    schema: __dirname + '/generated/schema.graphql',
    typegen: __dirname + '/generated/typings.ts',
  },
})

const server = new GraphQLServer({
  schema,
})

server.start(() => `Server is running on http://localhost:4000`)

More examples can be found in the /examples directory:

Documentation

You can find the docs for Nexus here.

Migrate from SDL

If you've been following an SDL-first approach to build your GraphQL server and want to see what your code looks like when written with GraphQL Nexus, you can use the SDL converter.

NPM DownloadsLast 30 Days