繁体   English   中英

使用包含和属性字段将 Apollo GraphQL 查询解析为 Sequelize 查询

[英]Parsing Apollo GraphQL query into Sequelize query with include and attributes fields

我正在与 Apollo 合作,为我的 GraphQL 请求构建解析器。

为了提高效率,我想获取请求的模型列表(带有相应的嵌套)以及从这些模型中的每一个请求的字段。 这样我就可以将这些信息传递给sequelize以仅在需要时加入模型 - 并且只提取必要的字段。

解析器确实在info对象中传递此信息。

(obj, args, { models }, info) => ...

info对象中,字段、嵌套模型及其各自选定的字段通过以下路径公开:

info.fieldNodes[0].selectionSet.selections

我的问题是将这个结构(以我想象的某种递归方式)解析为一个合理的结构,以便我传递给sequelize查询。

GraphQL 查询示例:

{
  getCompany(id: 1) {
    id
    name
    companyOffices {
      id
      users {
        id
        title
        userLinks {
          id
          linkUrl
        }
      }
    }
  }
}

它在info.fieldNodes[0].selectionSet.selections上生成以下内容(为了简洁起见,修剪一些字段):

[
   {
      "kind":"Field",
      "name":{
         "kind":"Name",
         "value":"id"
      }
   },
   {
      "kind":"Field",
      "name":{
         "kind":"Name",
         "value":"name"
      }
   },
   {
      "kind":"Field",
      "name":{
         "kind":"Name",
         "value":"companyOffices"
      },
      "selectionSet":{
         "kind":"SelectionSet",
         "selections":[
            {
               "kind":"Field",
               "name":{
                  "kind":"Name",
                  "value":"id"
               }
            },
            {
               "kind":"Field",
               "name":{
                  "kind":"Name",
                  "value":"users"
               },
               "selectionSet":{
                  "kind":"SelectionSet",
                  "selections":[
                     {
                        "kind":"Field",
                        "name":{
                           "kind":"Name",
                           "value":"id"
                        }
                     },
                     {
                        "kind":"Field",
                        "name":{
                           "kind":"Name",
                           "value":"title"
                        }
                     },
                     {
                        "kind":"Field",
                        "name":{
                           "kind":"Name",
                           "value":"userLinks"
                        },
                        "selectionSet":{
                           "kind":"SelectionSet",
                           "selections":[
                              {
                                 "kind":"Field",
                                 "name":{
                                    "kind":"Name",
                                    "value":"id"
                                 }
                              },
                              {
                                 "kind":"Field",
                                 "name":{
                                    "kind":"Name",
                                    "value":"linkUrl"
                                 }
                              }
                           ]
                        }
                     }
                  ]
               }
            }
         ]
      }
   }
]

使用此信息,我想生成如下查询:

  const company = await models.Company.findOne({
    where: { id: args.id },
    attributes: // DYNAMIC BASED ON QUERY
    include: // DYNAMIC BASED ON QUERY
  });

因此,我需要将上面的 GraphQL 查询解析为类似于上面info对象中的这种结构:

{
  attributes: ["id", "name"],
  include: [
    {
      model: "companyOffices",
      attributes: ["id"],
      include: [
        {
          model: users,
          attributes: ["id", "title"],
          include: [{ model: "userLinks", attributes: ["id", "linkUrl"] }]
        }
      ]
    }
  ]
};

但我不清楚如何通过递归实现这一点,而不会让事情变得混乱。 如果有更简单的方法来实现这种动态include / attributes我也愿意。

文艺青年最爱的-我怎么能阿波罗GraphQL查询的模型和领域转移到includeattributessequelize查询?

它可能会绕过这个问题,但我想知道像graphql-sequelize这样的东西是否可以帮助解决这样的问题。 如果没有,我已经使用此策略来完成您问题的属性部分。

const mapAttributes = (model, { fieldNodes }) => {
  // get the fields of the Model (columns of the table)
  const columns = new Set(Object.keys(model.rawAttributes));
  const requested_attributes = fieldNodes[0].selectionSet.selections
    .map(({ name: { value } }) => value);
  // filter the attributes against the columns
  return requested_attributes.filter(attribute => columns.has(attribute));
};
User: async (
    _, // instance (not used in Type resolver)
    { username, ... }, // arguments 
    { models: { User }, ... }, // context
    info,
  ) => {
    if (username) {  
      // (only requested columns queried)
      return User.findOne({
        where: { username },
        attributes: mapAttributes(User, info),
      });
    } ... 
  }

我终于找到了这个问题的解决方案(有点)。

const mapAttributes = (projectors, models) => {
    const map = {};
    const set = [];
    Object.keys(projectors).forEach((projector) => {
        if (typeof projectors[projector] === 'object') {
            map[projector] = mapAttributes(projectors[projector], models.slice(1));
        } else {
            set.push(projector);
            map[models[0]] = set;
        }
    });
    return map;
};

这里的projectors是 graphql 模式的对象符号,就像我们从info.fieldNodes[0].selectionSet.selections得到的对象一样

和模型,是迭代的有序方式。 所以在上面的例子中它会像

['company', 'companyOffices', 'users']等。

从最终的地图中,我们进入了一个整洁的结构,从中我们可以很好地获取属性。

最后,当您返回参数时,您可能需要将 sequelize 输出转换为 graphql 类型

const sequelizeToGraphql = (results = [], vouchers = [], postings = []) => {
    const final = { particulars: [] };
    results.forEach((result) => {
        vouchers.forEach((voucher) => {
            final[voucher] = result[voucher];
        });
        const obj = {};
        postings.forEach((posting) => {
            obj[posting] = result[`posting.${posting}`];
        });
        final.particulars.push(obj);
    });
    return final;
};

这里的voucherspostings是我sequqlize中给我的表名,同理自己修改

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM