tylim
12/02/2020, 8:55 PMtylim
12/02/2020, 9:02 PMimport { objectType } from '@nexus/schema'
export const PaymentMethod = objectType({
name: 'PaymentMethod',
definition(t) {
t.model.id()
t.model.user()
t.model.userId()
t.model.method({
resolve: async (root, args, ctx, info, originalResolve) => {
const isAuthorized = await ctx.authorization.byUserId.load(root.userId)
return isAuthorized
? originalResolve(root, args, ctx, info)
: 'UNAUTHORIZED'
},
})
t.model.reference({
resolve: async (root, args, ctx, info, originalResolve) => {
const isAuthorized = await ctx.authorization.byUserId.load(root.userId)
return isAuthorized
? originalResolve(root, args, ctx, info)
: 'unauthorized'
},
})
},
})
//========================
model PaymentMethod {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId String @unique
method PAYMENT_METHOD
reference String
}
//==================
enum PAYMENT_METHOD {
UNAUTHORIZED
CARD
BANK
PAYPAL
}
tylim
12/02/2020, 9:03 PMtylim
12/02/2020, 9:04 PMRyan
12/03/2020, 7:09 AMtylim
12/04/2020, 12:51 PMRyan
12/04/2020, 2:02 PMmodel User {
id String @id @default(uuid())
paymentMethods PaymentMethod[]
}
model PaymentMethod {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId String @unique
method PAYMENT_METHOD?
reference String?
}
enum PAYMENT_METHOD {
UNAUTHORIZED
CARD
BANK
PAYPAL
}
And the Nexus object:
const User = ns.objectType({
name: 'User',
definition(t) {
t.model.id()
t.model.paymentMethods()
},
})
const PaymentMethod = ns.objectType({
name: 'PaymentMethod',
definition(t) {
t.model.id()
t.model.user()
t.model.method()
t.model.reference()
},
})
I can create an auth rule like this: (you can add any custom auth logic here and return `true`/`false` based on the auth logic.
import { shield, rule } from 'graphql-shield'
import { Context } from '../types'
export const rules = {
isAuthenticatedUser: rule({ cache: 'contextual' })(
(_parent, _args, ctx: Context) => {
// auth logic will come here
return false
}
),
}
export const permissions = shield({
PaymentMethod: {
method: rules.isAuthenticatedUser,
reference: rules.isAuthenticatedUser,
},
})
And this will be added in my schema here:
new ApolloServer({
schema: applyMiddleware(await createSchema(), permissions),
...rest of the options
})
This will return null
for the related fields accessed by the client 🙂Ryan
12/04/2020, 2:05 PMnull
when unauthorized.tylim
12/04/2020, 4:27 PM