Skip to content

Commit

Permalink
add additional headers request
Browse files Browse the repository at this point in the history
  • Loading branch information
Perepecho Georgy committed Aug 15, 2018
1 parent 7de6340 commit 47d750d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 16 deletions.
10 changes: 5 additions & 5 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80,
"arrowParens": "always"
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80,
"arrowParens": "always"
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
37 changes: 27 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ class JsonRpcClient {

return counter;
};
})()
})();

constructor({
apiRoute,
headers = {},
withMeta,
}: {
}: {
apiRoute: string,
headers: {},
withMeta: boolean,
Expand All @@ -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 = {
Expand All @@ -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' });
Expand All @@ -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,
};
}
Expand Down

0 comments on commit 47d750d

Please sign in to comment.