簡體   English   中英

如何使用節點 js 在 GraphQL 中獲取響應狀態?

[英]How to get response status in GraphQL using node js?

在我的節點 js 代碼中

var express_graphql = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
    type Query {      
        getCandidateKey(email  : String): GetCandidateKey
    }

 type GetCandidateKey{
        CandidateID : Int
    }
`);

這里我正在執行存儲過程

var GetCandidateKey = async function (args) {
    let email = args.email
    let query = "exec getCandidateKey @EmailID='" + email + "';"; //executing stored procedures
    const pool = await poolPromise
    const result = await pool.request().query(query)
    return result.recordset[0]
}

根解析器

var root = {
    getCandidateKey: GetCandidateKey,
};

創建一個快速服務器和一個 GraphQL 端點

  app.use('/graphql', express_graphql({
        schema: schema,
        rootValue: root,
        graphiql: true
    }));

我得到的結果

在此處輸入圖像描述

如果查詢成功執行,我想要的結果

{
 "status" : "success"
  "data": {
    "getCandidateKey": {
      "CandidateID": 56
    }
  }
}

對於任何錯誤

    {
     "status" : "error"   //for throwing error
      "data": null    
    }

PS 我是 GraphQL 和 SQL 服務器的新手。

修改此 function 以便它發送所需的 object 作為響應。

var GetCandidateKey = async function (args) {
    try {
        let email = args.email
        let query = "exec getCandidateKey @EmailID='" + email + "';"; //executing stored procedures
        const pool = await poolPromise
        const result = await pool.request().query(query)
        return {
            status: 'success',
            data: result.recordset[0]
        };
    } catch (e) {
        return {
            status: 'error',
            data: null
        };
    }
}

並根據需要更改 GraphQL 類型。

更新

您可以使用以下架構:

var schema = buildSchema(`
    type Query {      
        getCandidateKey(email  : String): CandidateResponse
    }

    type CandidateResponse {
        status: String!
        data: GetCandidateKey
    }

    type GetCandidateKey {
        CandidateID : Int
    }
`);

暫無
暫無

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

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