在使用Proxy环境下使用graphql-request

这篇文章是关于在代理环境下使用graphql-request的笔记。

首先

graphql-request は、非常にシンプルで軽量な GraphQL のクライアント実装です。

npm: graphql-request

GitHub: graphql-request

環境 – 环境

我在下列环境中进行了操作确认。

    • Windows 10 Pro (64bit)

Git for Windows 2.20.1

Git Bash : GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)

Node.js 8.10.0

ここでは AWS Lambda でサポートされている最新の Node.js のバージョンに合わせています

npm 5.6.0
TypeScript 3.3

对 graphql-request 进行功能验证。

创建示例项目

打开 Git Bash,创建一个名为 node module 的文件夹。

$ mkdir sample-graphql
$ cd sample-graphql
$ npm init -y
Wrote to C:\work\sample-graphql\package.json:

{
  "name": "sample-graphql",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

安装 graphql-request。

在中文中进行同义复述,只需要一种选项:
使用 npm install 命令来安装 graphql-request 库。

$ npm install --save graphql-request
npm WARN registry Using stale data from https://registry.npmjs.org/ because the host is inaccessible -- are you offline?
npm WARN registry Using stale package data from https://registry.npmjs.org/ due to a request error during revalidation.
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN sample-graphql@1.0.0 No description
npm WARN sample-graphql@1.0.0 No repository field.

+ graphql-request@1.8.2
added 4 packages in 0.853s

创建示例代码

根据 graphql-request 的 Quickstart 创建一个示例代码。

const GraphQLClient = require('graphql-request').GraphQLClient;

const endpoint = 'https://api.graph.cool/simple/v1/movies';
const options = {};
const client = new GraphQLClient(endpoint, options);

const query = `{
  Movie(title: "Inception") {
    releaseDate
    actors {
      name
    }
  }
}`

const variables = {};

client.request(query, variables)
  .then(data => console.log(JSON.stringify(data, null, 2)))
  .catch(error => console.error(error));

运行样本代码

    非 Proxy 環境下での実行結果
$ node index.js
{
  "Movie": {
    "releaseDate": "2010-08-28T20:00:00.000Z",
    "actors": [
      {
        "name": "Leonardo DiCaprio"
      },
      {
        "name": "Ellen Page"
      },
      {
        "name": "Tom Hardy"
      },
      {
        "name": "Joseph Gordon-Levitt"
      },
      {
        "name": "Marion Cotillard"
      }
    ]
  }
}
    • Proxy 環境下での実行結果

接続できずにタイムアウトで失敗

$ node index.js
{ FetchError: request to https://api.graph.cool/simple/v1/movies failed, reason: connect ETIMEDOUT 13.33.0.193:443
    at ClientRequest.<anonymous> (C:\work\sample-graphql\node_modules\node-fetch\lib\index.js:1393:11)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  message: 'request to https://api.graph.cool/simple/v1/movies failed, reason: connect ETIMEDOUT 13.33.0.193:443',
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT' }

代理服务支持

安装 https-proxy-agent

https-proxy-agent 是一个通过代理连接 HTTPS 的 Node 模块。

$ npm install --save https-proxy-agent
npm WARN sample-graphql@1.0.0 No description
npm WARN sample-graphql@1.0.0 No repository field.

+ https-proxy-agent@2.2.1
added 6 packages in 1.766s

修改和执行示例代码

使用 graphql-request 时,它使用 node-fetch 并将通过构造函数中的选项参数传递给 Options。

const GraphQLClient = require('graphql-request').GraphQLClient;
const HttpsProxyAgent = require('https-proxy-agent');

const endpoint = 'https://api.graph.cool/simple/v1/movies';
const options = {
  agent: new HttpsProxyAgent(process.env.HTTP_PROXY),
};
const client = new GraphQLClient(endpoint, options);

const query = `{
  Movie(title: "Inception") {
    releaseDate
    actors {
      name
    }
  }
}`

const variables = {};

client.request(query, variables)
  .then(data => console.log(JSON.stringify(data, null, 2)))
  .catch(error => console.error(error));

执行结果

$ node index.js
{
  "Movie": {
    "releaseDate": "2010-08-28T20:00:00.000Z",
    "actors": [
      {
        "name": "Leonardo DiCaprio"
      },
      {
        "name": "Ellen Page"
      },
      {
        "name": "Tom Hardy"
      },
      {
        "name": "Joseph Gordon-Levitt"
      },
      {
        "name": "Marion Cotillard"
      }
    ]
  }
}

额外内容:对于TypeScript 的情况

创建 https-proxy-agent.d.ts

import { Agent } from 'http';

declare class HttpsProxyAgent extends Agent {
  constructor(uri: string | { protocol?: string; host?: string; hostname?: string; port?: string });
}

export = HttpsProxyAgent;

创建示例代码

import { GraphQLClient } from 'graphql-request';
import { Variables } from 'graphql-request/dist/src/types';
import HttpsProxyAgent from 'https-proxy-agent';

const endpoint = 'https://api.graph.cool/simple/v1/movies';
const options = {
  headers: {},
  agent: process.env.HTTP_PROXY ? new HttpsProxyAgent(process.env.HTTP_PROXY) : null,
};
const client = new GraphQLClient(endpoint, options);

const query = `{
  Movie(title: "Inception") {
    releaseDate
    actors {
      name
    }
  }
}`

const variables = {};

client.request(query, variables)
  .then(data => console.log(JSON.stringify(data, null, 2)))
  .catch(error => console.error(error));

广告
将在 10 秒后关闭
bannerAds