Skip to content

Commit

Permalink
feat: support request over proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
tasshi-me committed Aug 9, 2022
1 parent 17c772c commit a984693
Showing 1 changed file with 60 additions and 10 deletions.
70 changes: 60 additions & 10 deletions src/kintone/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { KintoneRestAPIClient } from "@kintone/rest-api-client";
const packageJson = require("../../package.json");
import HttpsProxyAgent from "https-proxy-agent";
import * as https from "https";
import fs from "fs";

export type RestAPIClientOptions = {
baseUrl: string;
Expand Down Expand Up @@ -40,24 +43,71 @@ const buildBasicAuthParam = (options: RestAPIClientOptions) => {
: {};
};

const buildClientCertAuth = (options: RestAPIClientOptions) => {
return options.pfxFilePath && options.pfxFilePassword
? {
clientCertAuth: {
pfxFilePath: options.pfxFilePath,
password: options.pfxFilePassword,
},
}
: {};
type ProxyConfig = {
protocol: string;
host: string;
port: number;
auth?: {
username: string;
password: string;
};
};

const buildProxyConfig = (proxy?: string): ProxyConfig | undefined => {
if (!proxy) {
return undefined;
}

const { protocol, hostname: host, port, username, password } = new URL(proxy);
let auth;
if (username.length > 0 && password.length > 0) {
auth = { username, password };
}
return {
protocol,
host,
port: Number(port),
auth,
};
};

const buildHttpsAgent = (options: {
proxy?: string;
pfxFilePath?: string;
pfxFilePassword?: string;
}): https.Agent => {
let pfx: string | Buffer | undefined;
if (options.pfxFilePath !== undefined) {
pfx = fs.readFileSync(options.pfxFilePath);
}
if (!options.proxy) {
return new https.Agent({ pfx, passphrase: options.pfxFilePassword });
}

const { protocol, hostname, port } = new URL(options.proxy);
return HttpsProxyAgent({
protocol: protocol,
host: hostname,
port: port,
pfx,
passphrase: options.pfxFilePassword,
});
};

export const buildRestAPIClient = (options: RestAPIClientOptions) => {
const httpsProxy =
process.env.HTTPS_PROXY ?? process.env.https_proxy ?? undefined;
return new KintoneRestAPIClient({
baseUrl: options.baseUrl,
auth: buildAuthParam(options),
...buildBasicAuthParam(options),
...buildClientCertAuth(options),
...(options.guestSpaceId ? { guestSpaceId: options.guestSpaceId } : {}),
userAgent: `${packageJson.name}@${packageJson.version}`,
proxy: buildProxyConfig(httpsProxy),
httpsAgent: buildHttpsAgent({
proxy: httpsProxy,
pfxFilePath: options.pfxFilePath,
pfxFilePassword: options.pfxFilePassword,
}),
});
};

0 comments on commit a984693

Please sign in to comment.