GraphQL中的多对多关系

时间:2018-04-18 15:10:05

标签: many-to-many graphql

假设我有两个对象阵列:

let movies = [
    { id: '1', title: 'Erin Brockovich'},
    { id: '2', title: 'A Good Year'},
    { id: '3', title: 'A Beautiful Mind'},
    { id: '4', title: 'Gladiator'}
];

let actors = [
    { id: 'a', name: 'Julia Roberts'},
    { id: 'b', name: 'Albert Finney'},
    { id: 'c', name: 'Russell Crowe'}
];

我想在他们之间建立多对多的关系。对于Vanilla JavaScript的开头,最终是在GraphQL架构中。

在JavaScript中,我做了类似的事情:

let movies = [
    { id: '1', title: 'Erin Brockovich',  actorId: ['a', 'b'] },
    { id: '2', title: 'A Good Year',      actorId: ['b', 'c'] },
    { id: '3', title: 'A Beautiful Mind', actorId: ['c'] },
    { id: '4', title: 'Gladiator',        actorId: ['c'] }
];
let actors = [
    { id: 'a', name: 'Julia Roberts', movieId: ['1'] },
    { id: 'b', name: 'Albert Finney', movieId: ['1', '2'] },
    { id: 'c', name: 'Russell Crowe', movieId: ['2', '3', '4'] }
];
let actorIds = [];
let movieIds = [];
for (let m = 0; m < movies.length; m ++) {
    for (let i = 0; i < movies[m].actorId.length; i ++) {
        actorIds.push(movies[m].actorId[i]);
    }
}
for (let a = 0; a < actors.length; a ++) {
    for (let i = 0; i < actors[a].movieId.length; i ++) {
        movieIds.push(actors[a].movieId[i]);
    }
}
for (let a = 0; a < actors.length; a ++) {
    for (let i = 0; i < actorIds.length; i ++) {
        if ((actors[a].id == 'c') && (actors[a].id == actorIds[i])) {
            for (let j = 0; j < movies.length; j ++) {
                if (movies[j].id == movieIds[i]) {
                    console.log(movies[j].title);
                }
            }
        }
    }
}

当我在Node中运行前面的代码时,终端将返回

A Good Year
A Beautiful Mind
Gladiator

这正是我想要的。

不幸的是我迷失在GraphQL架构中。到目前为止我所拥有的fields功能当然是这样的:

in_which_movies: {
    type: new GraphQLList(FilmType),
    resolve(parent, args) {

        let actorIds = [];
        let movieIds = [];

        for (let m = 0; m < movies.length; m ++) {
            for (let i = 0; i < movies[m].actorId.length; i ++) {
                actorIds.push(movies[m].actorId[i]);
            }
        }
        for (let a = 0; a < actors.length; a ++) {
            for (let i = 0; i < actors[a].movieId.length; i ++) {
                movieIds.push(actors[a].movieId[i]);
            }
        }
        for (var a = 0; a < actors.length; a ++) {
            for (var i = 0; i < actorIds.length; i ++) {
                if ((actors[a].id == parent.id) && (actors[a].id == actorIds[i])) {
                    for (var j = 0; j < movies.length; j ++) {
                        if (movies[j].id == movieIds[i]) {
                            console.log(movies[j].title);
                        }
                    }
                }
            }
        }
        return movies[j].title;
    }
}

当我在GraphiQL中运行以下查询...

{
    actor(id: "c") {
        name
        in_which_movies {
            title
        }
    }
}

......我有这样的答复:

{
  "errors": [
    {
      "message": "Cannot read property 'title' of undefined",
      "locations": [
        {
          "line": 4,
          "column": 3
        }
      ],
      "path": [
        "actor",
        "in_which_movies"
      ]
    }
  ],
  "data": {
    "actor": {
      "name": "Russell Crowe",
      "in_which_movies": null
    }
  }
}

...这对我来说很奇怪,因为终端正按照我的预期做出回应

A Good Year
A Beautiful Mind
Gladiator

我想我到目前为止所写的所有代码都没用,我需要一些新的指导如何在GraphQL中正确编写多对多关系。

1 个答案:

答案 0 :(得分:4)

TL; DR我认为你是在过度思考问题。您的解析器正在做太多的工作,这导致代码难以推理并且难以调试。

我不认为您的问题与GraphQL有很大关系,只是对您的基础数据进行正确的操作。我将尝试从您的示例和GraphQL开始逐步完成它,因此我们最终得到您正在寻找的类型和解析器。

从你的香草代码开始:

let movies = [
    { id: '1', title: 'Erin Brockovich',  actorId: ['a', 'b'] },
    { id: '2', title: 'A Good Year',      actorId: ['b', 'c'] },
    { id: '3', title: 'A Beautiful Mind', actorId: ['c'] },
    { id: '4', title: 'Gladiator',        actorId: ['c'] }
];
let actors = [
    { id: 'a', name: 'Julia Roberts', movieId: ['1'] },
    { id: 'b', name: 'Albert Finney', movieId: ['1', '2'] },
    { id: 'c', name: 'Russell Crowe', movieId: ['2', '3', '4'] }
];

我想建议我们将其转换为id索引的内容,以便查询更容易。这也将更好地模拟您通常在生产GraphQL API背后的数据库或键值存储。

将其转换为索引的内容,但仍然是vanilla JS:

let movies = {
    '1': { id: '1', title: 'Erin Brockovich',  actorId: ['a', 'b'] },
    '2': { id: '2', title: 'A Good Year',      actorId: ['b', 'c'] },
    '3': { id: '3', title: 'A Beautiful Mind', actorId: ['c'] },
    '4': { id: '4', title: 'Gladiator',        actorId: ['c'] }
};
let actors = {
    'a': { id: 'a', name: 'Julia Roberts', movieId: ['1'] },
    'b': { id: 'b', name: 'Albert Finney', movieId: ['1', '2'] },
    'c': { id: 'c', name: 'Russell Crowe', movieId: ['2', '3', '4'] }
};

接下来,我们应该考虑代表这些类型的GraphQL架构。这里是“多对多”部分发挥作用的地方。我认为我们可以非常干净地从您的示例数据中获取类型:

type Movie {
  id: ID!
  title: String
  actors: [Actor]
}

type Actor {
  id: ID!
  name: String
  movies: [Movie]
}

请注意[Movie]Movie个对象的列表。即使底层数据包含id(也就是“标准化”,这是我们所期望的),我们根据实际的类型关系对API进行建模。

接下来我们需要设置解析器。让我们来看看Actor类型的解析器,因为这就是你的例子中的内容。

movies: {
    type: new GraphQLList(FilmType),
    resolve(parent) {
        // The ids of all the movies this actor is in. "parent" will be the
        // actor data currently being queried
        let movieIds = parent.movieId;
        // We'll build up a list of the actual movie datas to return.
        let actorInMovies = [];
        for (let m = 0; m < movieIds.length; m++) {
            // The m'th movie id.
            let movieId = movieIds[m];
            // The movie data from our indexed "movies" top level object.
            // In production, this might access a database service
            let movie = movies[movieID];
            // Add that movie to the list of movies
            actorInMovies.push(movie)
        }
        // Then we'll return that list of movie objects.
        return actorInMovies;
    }
}

请注意,在原始解析程序中,您返回的movies[j].title可能是一个字符串,与“FilmType列表”所期望的不匹配,并且在上面的示例中是一个电影数组返回数据对象。

此外,上面的代码是一种非常详细的方法,但我认为评论每一步都会有所帮助。要真正实现多对多,Movie类型的actors字段应具有几乎完全相同的代码。但是,为了展示如何使用.map()运算符大大简化此代码的示例,我将以另一种方式编写:

actors: {
    type: new GraphQLList(ActorType),
    resolve(parent) {
        // In this case, "parent" will be the movie data currently being queried.
        // Use "map" to convert a list of actor ids into a list of actor data 
        // objects using the indexed "actors" top level object.
        return parent.actorId.map(id => actors[id]);
    }
}