growwapi
Version:
NodeJS SDK for Groww trading APIs
40 lines (39 loc) • 1.25 kB
JavaScript
import { Auth } from '../resources/auth';
import camelcaseKeys from 'camelcase-keys';
export class HttpClient {
constructor(baseUrl, basePath = '') {
this.baseUrl = baseUrl;
this.basePath = basePath;
}
url(path) {
return `${this.baseUrl}${this.basePath}${path}`;
}
async get(path) {
const res = await fetch(this.url(path), {
headers: await this.headers()
});
return (await this.handleResponse(res)).payload;
}
async post(path, body) {
const res = await fetch(this.url(path), {
method: 'POST',
headers: await this.headers(),
body: JSON.stringify(body)
});
return (await this.handleResponse(res)).payload;
}
async headers() {
const accessToken = await Auth.getAccessToken();
return {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'x-client-platform': 'growwapi-nodejs-client',
};
}
async handleResponse(res) {
if (!res.ok)
throw new Error(await res?.text());
const jsonResponse = await res.json();
return camelcaseKeys(jsonResponse, { deep: true });
}
}