如何在GraphQL解析器中动态访问正在查询的字段的名称? [英] How to dynamically access the names of fields being queries in a GraphQL resolver?

查看:69
本文介绍了如何在GraphQL解析器中动态访问正在查询的字段的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏夹:

dbPosts

id: mongoose.Schema.Types.ObjectId,
title: { type: String },
content: { type: String },
excerpt: { type: String },
slug: { type: String },
author: {
   id: { type: String },
   fname: { type: String },
   lname: { type: String },
}

dbAuthors

id: mongoose.Schema.Types.ObjectId,
fname: { type: String },
lname: { type: String },
posts: [
         id: { type: String },
         title: { type: String }
       ]

我按以下方式解决我的作者查询:

I resolve my author queries as follows:

Query: {
    authors: (parent, root, args, context) => {
      return dbAuthor.find({});
    },
    author: (root, args, context) => {
      return dbAuthor.findById(args.id);
    },
  },

  Author: {
    posts: (parent) => {
      if(parent.posts) {
        return parent.posts;
      } else {
        return dbAuthor.find({'author.id': parent.id});
      }
    },
  }

我要解决的原因是通过使我的关系非规范化来优化我的MongoDB请求.这是目标:

The reason I'm resolving thus is to optimize my MongoDB requests by denormalizing my relationships. Here's the objective:

如果仅需要列出具有其作品标题的作者,则所有必需的字段都在dbAuthors中,因此无需查找dbPosts.但是,如果您需要返回的每个帖子的更多细节(例如节选或or),则可以在dbPosts中查找以下情况:

If you need just a list of authors with the titles of their works, all necessary fields are right there in dbAuthors, so no need to look up dbPosts. But if you need more details on each post returned, say, excerpts or slug, you look up dbPosts for the following condition:

{'author.id': parent.id}

但是问题是,如果您的查询看起来像这样:

But the problem is, if your query looks like this:

authors(id: "3") {
  fname
  lname
  posts {
    title
    excerpt
  }
}

它中断了,因为父对象中没有返回摘录字段.如果可以通过某种方式确定正在作者字段中查询哪些字段,然后确定在父级中返回的值是否足够,则可以轻松解决此问题.如果不是,那么我可以继续使用作者的id值查找dbPosts.是否可以?因为否则,Mongo会强烈敦促您这么做,这将破坏使收藏集不规范化的整个目的!

it breaks, because there's no excerpt field returned in the parent object. This problem could be easily fixed if there were some way I could determine what fields are being queried on an author's posts field and then decide if the values returned in parent would suffice. If not, I could then proceed to look up dbPosts with the author's id value. Is it possible? Because if not, it would defeat the whole purpose of denormalizing your collections, something Mongo strongly urges you to do!

推荐答案

相当规范化-数据已重复;)

It's rather denormalized - data is duplicated ;)

您可能正在寻找 info.fieldNodes

这篇关于如何在GraphQL解析器中动态访问正在查询的字段的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆