From 47d750dda044a556c3415c7edb854d1a15ddb287 Mon Sep 17 00:00:00 2001 From: Perepecho Georgy Date: Wed, 15 Aug 2018 11:07:51 +0300 Subject: [PATCH] add additional headers request --- .prettierrc | 10 +++++----- package.json | 2 +- src/index.js | 37 +++++++++++++++++++++++++++---------- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/.prettierrc b/.prettierrc index 4f2094a..fa06ac0 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,7 +1,7 @@ { - "tabWidth": 4, - "singleQuote": true, - "trailingComma": "es5", - "printWidth": 80, - "arrowParens": "always" + "tabWidth": 4, + "singleQuote": true, + "trailingComma": "es5", + "printWidth": 80, + "arrowParens": "always" } diff --git a/package.json b/package.json index c47417b..9c88c37 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "build": "gulp build", "prepare": "npm run build", "release": "release-it --no-npm.publish", - "publish": "npm publish" + "publish-npm": "npm publish" }, "repository": { "type": "git", diff --git a/src/index.js b/src/index.js index 69c4d21..1bc4803 100644 --- a/src/index.js +++ b/src/index.js @@ -24,13 +24,13 @@ class JsonRpcClient { return counter; }; - })() + })(); constructor({ apiRoute, headers = {}, withMeta, - }: { + }: { apiRoute: string, headers: {}, withMeta: boolean, @@ -40,28 +40,39 @@ class JsonRpcClient { this.withMeta = withMeta; } - asCurl(method: string, params: {}, id: number) { - const options = { + asCurl( + method: string, + params: {}, + id: number, + options: { headers: {} } = { headers: {} } + ) { + const body = { jsonrpc: '2.0', method, params, id, }; - const headers = Object.keys(this.headers).map( - (key) => `-H '${key}: ${this.headers[key]}'` + const allHeaders = { ...this.headers, ...options.headers }; + + const headers = Object.keys(allHeaders).map( + (key) => `-H '${key}: ${allHeaders[key]}'` ); return [ 'curl -i', '-X POST', headers.join(' '), - `--data-binary '${JSON.stringify(options)}'`, + `--data-binary '${JSON.stringify(body)}'`, `'${this.apiRoute}'`, ].join(' '); } - request(method: string, params: {}) { + request( + method: string, + params: {}, + options: { headers: {} } = { headers: {} } + ) { this.requestId = JsonRpcClient.getUniqId(); const body = { @@ -73,9 +84,13 @@ class JsonRpcClient { const startTime = new Date(); + const headers = { ...this.headers, ...options.headers }; + return new Promise((resolve, reject) => { axios - .post(this.apiRoute, body, { headers: this.headers }) + .post(this.apiRoute, body, { + headers, + }) .then(({ data: res }) => { if (!res) { reject({ error: 'Unknown error' }); @@ -94,7 +109,9 @@ class JsonRpcClient { if (this.withMeta) { meta = { - curl: this.asCurl(method, params, this.requestId), + curl: this.asCurl(method, params, this.requestId, { + headers, + }), timeRequest: new Date() - startTime, }; }