GraphQL Schema: Nexus
![Nexus Logo](/img/nexus-optim.png)
The back-and-forth between the schema declaration and resolvers is something I always found laborious when writing GraphQL APIs, and the fact that it is not DRY makes it prone to typos. That's why I now prefer using code-first approach with Nexus, which can also generate TypeScript types to make the whole experience much more pleasant.
Might change soon? PossiblySetup
- Yarn
- NPM
yarn add nexus
npm i nexus
import { join } from 'path'
import { makeSchema } from 'nexus'
import * as types from './types'
const schema = makeSchema({
types,
outputs: process.env.TS_NODE_DEV
? {
typegen: join(__dirname, '../../../../node_modules/@types/nexus-typegen/index.d.ts'),
schema: join(__dirname, 'schema.graphql'),
}
: {},
})
export default schema
The schema is defined in files like those:
export * from './scalars'
export * from './user'
import { VoidResolver } from 'graphql-scalars'
import { asNexusMethod } from 'nexus'
export const VoidScalar = asNexusMethod(VoidResolver, 'void')
import { objectType, extendType } from 'nexus'
export const User = objectType({
name: 'User',
definition: t => {
t.string('name')
},
})
export const UserQueries = extendType({
type: 'Query',
definition: t => {
t.nonNull.list.field('users', {
type: 'User',
resolve: () => [{ name: 'Foo' }],
})
},
})
Nexus cannot seem to be authorized to generate the schema and TypeScript types while running on a Vercel serverless function (EROFS: read-only file system
), so we need to run an NPM script manually after making schema changes:
"nexus-schema": "ts-node --transpile-only src/lib/api/graphql/schema.ts"
Prisma Plugin for Nexus
TODO: nexus-plugin-prisma
Alternatives
I have not tried TypeGraphQL yet, but it seems like it would integrate well with TypeORM. In terms of code style, I do have a bit of a preference for plain functions over classes and decorators, but that's not a deal-breaker at all. Since Nexus is made by Prisma, and has a plugin for Prisma, it seems like a natural choice to either pick Prisma + Nexus, or TypeORM + TypeGraphQL.