nexus-plugin-shield
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

nexus-plugin-shield

Unlock the power of graphql-shield in your nexus app

Installation

npm install nexus-plugin-shield

Known limitations

  • fragments not supported

Example Usage

Setup

// app.ts
 
import { use } from 'nexus'
import { shield, rule, deny, not, and, or } from 'nexus-plugin-shield'
 
const isAuthenticated = rule({ cache: 'contextual' })(
  async (parent, args, ctx: NexusContext, info) => {
    return ctx.user !== null
  }
)
 
const isAdmin = rule({ cache: 'contextual' })(
  async (parent, args, ctx: NexusContext, info) => {
    return ctx.user.role === 'admin'
  }
)
 
const isEditor = rule({ cache: 'contextual' })(
  async (parent, args, ctx: NexusContext, info) => {
    return ctx.user.role === 'editor'
  }
)
 
const permissions = shield({
  rules: {
    Query: {
      frontPage: not(isAuthenticated),
      fruits: and(isAuthenticated, or(isAdmin, isEditor)),
      customers: and(isAuthenticated, isAdmin),
    },
    Mutations: {
      addFruitToBasket: isAuthenticated,
    },
    Fruit: isAuthenticated,
    Customer: isAdmin,
  },
  options: {
    fallbackRule: deny,
  },
})
 
use(permissions)

shield({rules: rules, options: options})

rules

A rule map must match your schema definition.

graphql-shield documentation

options

graphql-shield documentation

Context type

Nexus provide a global NexusContext interface you can use in your rules:

rule()(async (parent, args, context: NexusContext, info) => {
  // logic
})

Package Sidebar

Install

npm i nexus-plugin-shield

Weekly Downloads

107

Version

0.2.0

License

MIT

Unpacked Size

14.2 kB

Total Files

15

Last publish

Collaborators

  • lvauvillier