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

时间:2019-05-15 10:43:30

标签: javascript recursion graphql sequelize.js apollo

我正在与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
  });

所以我需要从上面的info对象中解析出上面的GraphQL查询,像这样的结构:

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

但是我不清楚如何在不使事情变得混乱的情况下通过递归实现这一目标。如果有一种更简单的方法来实现这种动态include / attributes,我也对此持开放态度。

tl; dr-如何将Apollo GraphQL查询的模型和字段转移到include查询的attributessequelize中? < / p>

2 个答案:

答案 0 :(得分:0)

可能正在解决问题,但我想知道类似graphql-sequelize的方法是否可以帮助解决此类问题。如果没有,我就用this strategy完成问题的属性部分。

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),
      });
    } ... 
  }

答案 1 :(得分:0)

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

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 schema 的对象符号,和我们从 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中的表名,同理自己修改