簡體   English   中英

如何重用GraphQL個人查詢API來獲取列表?

[英]How to reuse GraphQL individual query API to get the list?

我正在嘗試獲取模型列表。

首先,我創建了一個模型查詢API。 現在我想通過提供ids來獲得列表。

我知道我可以在getModelById上使用Promise.all並對我再次得到的每個結果進行一些處理。

但是,有沒有一種方法可以重用各個模型查詢API? 謝謝

const ModelType = new GraphQLObjectType({
  name: 'Model',
  fields: {
    id: { type: GraphQLString },
    // ...
  }
});

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: () => ({
    model: {
      type: ModelType,
      args: {
        id: { type: GraphQLString }
      },
      resolve(parentValue, args) {
        const { id } = args;
        return getModelById(id).then(model => doSomeProcessing(model));
      }
    },

    models: {
      type: new GraphQLList(ModelType),
      args: {
        ids: { type: new GraphQLList(GraphQLString) }
      },
      resolve(parentValue, args) {
        const { ids } = args;
        // here I know I can use Promise.all on getModelById and do my doSomeProcessing again for each result I got,
        // but is there a way to reuse the model query above? Thanks
      }
    }
  })
});

您不能引用另一個解析器中的現有解析器。 重用邏輯的唯一方法是將其抽象為一個單獨的函數,兩個解析器都將調用該函數。 例如:

const getProcessedModelById = (id) => {
  return getModelById(id).then(model => doSomeProcessing(model))
}

// model
resolve(parentValue, args) {
  return getProcessedModelById(args.id)
}

// models
resolve(parentValue, args) {
  return Promise.all(args.ids.map(id => getProcessedModelById(args.id)))
}

根據您對模型進行的處理類型的不同,可能可以通過Model類型的字段解析器進行處理。 假設您的Model類型有兩個字段firstNamelastName但是您的模型返回一個名為name字段。 您的doSomeProcessing只是采用該名稱並將其分解為firstNamelastName

function doSomeProcessing (model) {
  const names = model.name.split(' ')
  return { firstName: names[0], lastName: names[1] }
}

不用這樣做,您的解析器可以只返回getModelById返回的任何內容。 然后,您可以將“處理”邏輯封裝在每個字段的解析器中:

// firstName field
resolve (parentValue) {
  return parentValue.name.split(' ')[0]
}

// lastName field
resolve (parentValue) {
  return parentValue.name.split(' ')[1]
}

這種方法的優點是,除非客戶端請求該字段,否則“處理”實際上不會發生。 在這個非常簡單的示例中,解決lastName字段並不昂貴,但是並非總是如此。 它還非常巧妙地封裝了從基礎數據層派生的字段的邏輯。 但是,它也可能最終變得更昂貴(例如,想象一下,如果split調用本身就很昂貴……現在,我們要兩次而不是一次地調用該方法)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM