GraphQL-将布尔变量添加到子graphql对象以授予用户操作

时间:2019-03-29 08:08:13

标签: graphql

我正在构建一个平台,人们可以在该平台上创建和共享帖子并对其发表评论。我想在架构中的postType和commentType的graphql对象上添加一个“可编辑”布尔变量,如果登录的用户ID相同,则为true,如果登录的用户ID是post / comment。

这是我的帖子和评论graphql类型:

    const PostType = new GraphQLObjectType({
    name: "Post",
    fields: () => ({
        id: { type: GraphQLID },
        title: { type: new GraphQLNonNull(GraphQLString) },
        content: { 
            type: new GraphQLNonNull(GraphQLString)
        },
        container: { 
            type: ContainerType,
            resolve: async function(parent, args) {
                return await Container.findById(parent.containerId)
            }
        },
        user: { 
            type: new GraphQLNonNull(UserType),
            resolve: async function(parent, args) {
                return await User.findById(parent.userId)
            }
        },
        votes: { type: GraphQLInt },
        comments: {
            type: GraphQLList(CommentType),
            resolve: async function (parent, args) {
                return await Comment.find({ postId: parent.id.toString() })
            }
        },
        createdAt: { type: GraphQLString },
        updatedAt: { type: GraphQLString },
        editable: { 
            type: GraphQLBoolean,
        },
    })
})

const CommentType = new GraphQLObjectType({
    name: "Comment",
    fields: () => ({
        id: { type: GraphQLID },
        content: { type: new GraphQLNonNull(GraphQLString) },
        user: { 
            type: new GraphQLNonNull(UserType),
            resolve: async function(parent, args) {
                return await User.findById(parent.userId)
            }
        },
        parent: { 
            type: CommentType,
            resolve: async function(parent, args) {
                return await Comment.findById(parent.parentId)
            }
        },
        post: { 
            type: new GraphQLNonNull(PostType),
            resolve: async function(parent, args) {
                return await Post.findById(parent.postId)
            }
        },
        votes: { type: GraphQLInt },
        editable: { type: GraphQLBoolean }
    })
})

现在,当我调用帖子时,我会同时调用这些帖子的评论(感谢GraphQL),但是我只能在帖子上添加此过滤器,因为它们可以直接访问,但不能直接评论是从幕后的graphql中检索到的,因此这是查询和解析器示例之一:

allPosts: {
        type: GraphQLList(PostType),
        args: {
            token: { type: new GraphQLNonNull(GraphQLString) }
        },
        resolve: async function(parent, args) {
            let data = verifyToken(args.token)
            if (!data) {
                return new Error ("invalid token")
            }
            let posts = await Post.find({ })
            await posts.map(post => {
                post.editable = post.userId.toString() === data.id ? true : false
            })
            return posts
        }
    },

那么,如何为通过帖子检索的评论添加相同的过滤器?

0 个答案:

没有答案