2016-03-02 28 views
9

您如何在GraphQL中編寫查詢解析器,並且在關係數據庫中表現良好?什麼是解決相關對象的慣用,高性能的方法?

使用來自this tutorial的示例模式,假設我有一個簡單的數據庫,其中包含usersstories。用戶可以創作多個故事,但故事只有一個用戶作爲其作者(爲簡單起見)。

查詢某個用戶時,可能還需要獲取該用戶創作的所有故事的列表。一個可能定義一個GraphQL查詢來處理(從上面的鏈接教程被盜):

const Query = new GraphQLObjectType({ 
    name: 'Query', 
    fields:() => ({ 
    user: { 
     type: User, 
     args: { 
     id: { 
      type: new GraphQLNonNull(GraphQLID) 
     } 
     }, 
     resolve(parent, {id}, {db}) { 
     return db.get(` 
      SELECT * FROM User WHERE id = $id 
      `, {$id: id}); 
     } 
    }, 
    }) 
}); 

const User = new GraphQLObjectType({ 
    name: 'User', 
    fields:() => ({ 
    id: { 
     type: GraphQLID 
    }, 
    name: { 
     type: GraphQLString 
    }, 
    stories: { 
     type: new GraphQLList(Story), 
     resolve(parent, args, {db}) { 
     return db.all(` 
      SELECT * FROM Story WHERE author = $user 
     `, {$user: parent.id}); 
     } 
    } 
    }) 
}); 

預期這將工作;如果我查詢特定的用戶,如果需要的話,我也可以獲取該用戶的故事。但是,這並不理想。當需要使用JOIN的單個查詢時,它需要兩次到數據庫。如果我查詢多個用戶,問題會被放大 - 每個額外的用戶都會導致額外的數據庫查詢。越深入地遍歷我的對象關係,問題就會呈指數級地惡化。

此問題是否解決?有沒有辦法編寫一個查詢解析器,不會導致生成低效的SQL查詢?

回答

8

這種問題有兩種方法。

Facebook使用的一種方法是將請求發生在一個tick中,並在發送之前將它們組合在一起。通過這種方式,您可以執行一個請求來檢索有關多個用戶的信息,而不是爲每個用戶提出請求。丹·謝弗寫了一個good comment explaining this approach。 Facebook發佈了Dataloader,這是該技術的一個示例實現。

// Pass this to graphql-js context 
const storyLoader = new DataLoader((authorIds) => { 
    return db.all(
    `SELECT * FROM Story WHERE author IN (${authorIds.join(',')})` 
).then((rows) => { 
    // Order rows so they match orde of authorIds 
    const result = {}; 
    for (const row of rows) { 
     const existing = result[row.author] || []; 
     existing.push(row); 
     result[row.author] = existing; 
    } 
    const array = []; 
    for (const author of authorIds) { 
     array.push(result[author] || []); 
    } 
    return array; 
    }); 
}); 

// Then use dataloader in your type 
const User = new GraphQLObjectType({ 
    name: 'User', 
    fields:() => ({ 
    id: { 
     type: GraphQLID 
    }, 
    name: { 
     type: GraphQLString 
    }, 
    stories: { 
     type: new GraphQLList(Story), 
     resolve(parent, args, {rootValue: {storyLoader}}) { 
     return storyLoader.load(parent.id); 
     } 
    } 
    }) 
}); 

雖然這不能解決高效SQL,它仍然可能是許多用例不夠好,會讓東西跑得更快。對於不允許JOIN的非關係數據庫來說,這也是一個好方法。

另一種方法是在解析函數中使用有關請求字段的信息,以在相關時使用JOIN。解析上下文有已解析當前解析的查詢部分的AST的fieldASTs字段。通過查看AST(selectionSet)的子代,我們可以預測是否需要連接。一個非常簡化和笨重的例子:

const User = new GraphQLObjectType({ 
    name: 'User', 
    fields:() => ({ 
    id: { 
     type: GraphQLID 
    }, 
    name: { 
     type: GraphQLString 
    }, 
    stories: { 
     type: new GraphQLList(Story), 
     resolve(parent, args, {rootValue: {storyLoader}}) { 
     // if stories were pre-fetched use that 
     if (parent.stories) { 
      return parent.stories; 
     } else { 
      // otherwise request them normally 
      return db.all(` 
      SELECT * FROM Story WHERE author = $user 
     `, {$user: parent.id}); 
     } 
     } 
    } 
    }) 
}); 

const Query = new GraphQLObjectType({ 
    name: 'Query', 
    fields:() => ({ 
    user: { 
     type: User, 
     args: { 
     id: { 
      type: new GraphQLNonNull(GraphQLID) 
     } 
     }, 
     resolve(parent, {id}, {rootValue: {db}, fieldASTs}) { 
     // find names of all child fields 
     const childFields = fieldASTs[0].selectionSet.selections.map(
      (set) => set.name.value 
     ); 
     if (childFields.includes('stories')) { 
      // use join to optimize 
      return db.all(` 
      SELECT * FROM User INNER JOIN Story ON User.id = Story.author WHERE User.id = $id 
      `, {$id: id}).then((rows) => { 
      if (rows.length > 0) { 
       return { 
       id: rows[0].author, 
       name: rows[0].name, 
       stories: rows 
       }; 
      } else { 
       return db.get(` 
       SELECT * FROM User WHERE id = $id 
       `, {$id: id} 
      ); 
      } 
      }); 
     } else { 
      return db.get(` 
      SELECT * FROM User WHERE id = $id 
      `, {$id: id} 
     ); 
     } 
     } 
    }, 
    }) 
}); 

請注意,這可能有問題,例如,片段。但是也可以處理它們,這只是一個更詳細地檢查選擇集的問題。

graphql-js存儲庫中目前有一個PR,它允許通過在上下文中提供「解決方案」來編寫更復雜的查詢優化邏輯。

+0

啊,我注意到'fieldASTs'參數之前,但現在我看到一個具體的用例,它變得更有意義。謝謝! – ean5533

相關問題