Nexus Schema
Declarative, code-first and strongly typed GraphQL schema construction for TypeScript & JavaScript
Note
The nexus
package is becoming the Nexus framework. Learn more about the transition in #373. Learn how to migrate your app to the framework in the migration guide. Don't worry, you will be able to continue using this schema component standalone.
Overview
- Code-first: Programmatically define your GraphQL types in JavaScript/TypeScript
- Compatible with the GraphQL ecosystem: Nexus is based on
graphql-js
- Type-safe: Nexus enables auto-completion and error checks in your IDE (even for JS)
- Generates SDL & TS definitions: SDL schema and typings are updated as you code
Examples
"Hello World" GraphQL server with graphql-yoga
import { queryType, stringArg, makeSchema } from "@nexus/schema";
import { GraphQLServer } from "graphql-yoga";
const Query = queryType({
definition(t) {
t.string("hello", {
args: { name: stringArg({ nullable: true }) },
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`);
All examples of Nexus Schema can be found in the /examples
directory:
Features
- Expressive, declarative API for building schemas
- 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
- Assumes non-null by default, but makes this configurable on per-schema/per-type basis
- 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
- Lots of good examples to get you started and thorough API documentation
- Full type-safety for free
- Internal structure allows library authors to build more advanced abstractions
- Independent from Prisma, but integrates nicely using the
nexus-prisma
plugin - Allows code re-use by creating higher level "functions" which wrap common fields
Documentation
You can find the docs for Nexus Schema here.
Install
Nexus Schema can be installed via the @nexus/schema
package. It also requires graphql
as a peer dependency:
npm install --save @nexus/schema graphql
or
yarn add @nexus/schema graphql
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: