【发布时间】:2016-09-18 06:57:34
【问题描述】:
我如何检查用户是否有权查看或查询某些东西?我不知道该怎么做。
- 在
args?这怎么行? - 在
resolve()?查看用户是否有权限并以某种方式 消除/更改一些参数?
示例:
如果用户是“访问者”,他只能看到公开的帖子,“管理员”可以看到一切。
const userRole = 'admin'; // Let's say this could be "admin" or "visitor"
const Query = new GraphQLObjectType({
name: 'Query',
fields: () => {
return {
posts: {
type: new GraphQLList(Post),
args: {
id: {
type: GraphQLString
},
title: {
type: GraphQLString
},
content: {
type: GraphQLString
},
status: {
type: GraphQLInt // 0 means "private", 1 means "public"
},
},
// MongoDB / Mongoose magic happens here
resolve(root, args) {
return PostModel.find(args).exec()
}
}
}
}
})
更新 - Mongoose 模型看起来像这样:
import mongoose from 'mongoose'
const postSchema = new mongoose.Schema({
title: {
type: String
},
content: {
type: String
},
author: {
type: mongoose.Schema.Types.ObjectId, // From user model/collection
ref: 'User'
},
date: {
type: Date,
default: Date.now
},
status: {
type: Number,
default: 0 // 0 -> "private", 1 -> "public"
},
})
export default mongoose.model('Post', postSchema)
【问题讨论】: