簡體   English   中英

GraphQL 查詢在 GraphiQL 中返回 NULL,但數據出現在控制台日志中

[英]GraphQL query return NULL in GraphiQL, but data appears in console log

我有一個 GraphQL API 應該從 MySQL 和 PostGres 數據庫返回數據。 在解析器中,我有 console.log 結果,可以在終端中查看數據。

address: {
      type: AddressType,
      description: "An Address",
      args: {
        id: { type: GraphQLInt },
      },
      resolve: (parent, args) => {
        // Make a connection to MySQL
        let result;
        connection.query(
          `SELECT * FROM addresses WHERE id = ${args.id}`,
          (err, res, fields) => {
            if (err) console.log(err);
            console.log("========");
            console.log(res);
            console.log("+++++++++");
            console.log(res[0]);

            // console.log(result);
          }
        );
        return result;
      },
    },

在終端中,我可以在 GraphiQL 上運行查詢時看到結果:

[nodemon] starting `node schema.js`
Server is running
Connected to PSQL database.
Connected to mySQL database.
========
[
  RowDataPacket {
    id: 1,
    address_type: 'House',
    status: 'Inactive',
    entity: 'Building',
    number_and_street: 'PO BOX 276',
    suite_and_apartment: 'PO',
    city: 'Ennis',
    postal_code: '59729-0276',
    country: 'USA',
    notes: 'Dolorem quia repellendus et et nobis.',
    created_at: 2020-12-18T05:00:00.000Z,
    updated_at: 2021-05-21T04:00:00.000Z,
    latitude: null,
    longitude: null
  }
]
+++++++++
RowDataPacket {
  id: 1,
  address_type: 'House',
  status: 'Inactive',
  entity: 'Building',
  number_and_street: 'PO BOX 276',
  suite_and_apartment: 'PO',
  city: 'Ennis',
  postal_code: '59729-0276',
  country: 'USA',
  notes: 'Dolorem quia repellendus et et nobis.',
  created_at: 2020-12-18T05:00:00.000Z,
  updated_at: 2021-05-21T04:00:00.000Z,
  latitude: null,
  longitude: null
}

但是在 GraphiQL 上,我得到 null 的數據。 輸入:

{
  address(id: 1) {
    address_type
  }
  }

output:

{
  "data": {
    "address": null
  }
}

我對 GraphQL 很陌生。 我在這里能錯過什么? 我正在嘗試從終端獲取此信息,以便在 GraphiQL 中查詢時顯示。 只是想了解更多。

注意力不集中的經典問題:您將res變量用於控制台。 而且您沒有為result賦值。

並且在執行查詢之前執行return result (脫離你有數據的上下文)

請參閱文檔以了解如何使用async / await語法。 您當前正在使用回調 - 這不是推薦的語法。

不確定,但應該類似於,您應該使用async/await並等待query數據的返回。 還要確保將值分配給您擁有的變量:

address: {
  type: AddressType,
  description: "An Address",
  args: {
    id: { type: GraphQLInt },
  },
  resolve: async (parent, args) => {
    const result = await connection.query('SELECT * FROM addresses WHERE id = $1', [args.id]);
    
    return result;
  },
},

最終為我工作的是以下內容:

address: {
      type: AddressType,
      description: "An Address",
      args: {
        id: { type: GraphQLInt },
      },
      resolve: async (parent, args) => {
        const [rows, fields] = await promisePool.query(
          `SELECT * FROM addresses WHERE id = ${args.id}`
        );
        console.log(rows[0]);
        return rows[0];
      },
    },

暫無
暫無

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

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