import Hmmac from 'hmmac-es6';
import axios from 'axios';
import url from 'url'
const HMMAC = new Hmmac();
export class GalaServerApi {
client = axios.create({
baseURL: this.baseUri,
responseType: 'json',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
});
constructor(
key: string,
secret: string,
private baseUri: string,
) {
// on every HTTP request to the Gala platform
this.client.interceptors.request.use(config => {
// Create new request based on intercepted request
const request = { ...config };
const parsedUrl = url.parse(request.url);
// Construct request information for signing
const signed: any = {
host: parsedUrl.hostname.toLowerCase(),
path: parsedUrl.path,
method: request.method.toUpperCase(),
headers: {
...request.headers,
Date: new Date().toUTCString(),
}
};
// Add body data if present
if (request.data) {
signed.body = request.data;
}
// Sign the request with our key and secret
HMMAC.sign(signed, { key, secret });
// Copy over signed request header
Object.assign(request.headers, signed.headers);
return request;
})
}
getItems(userId: string): Promise<GalaItem[]> {
return this.client({
method: 'get',
url: `${this.baseUri}/items/${userId}`,
}).then(response => response.data)
}
getBalance(userId: string): Promise<{ gala: string }> {
return this.client({
method: 'get',
url: `${this.baseUri}/gala/balance/${userId}`,
}).then(response => response.data)
}
getCraftableItems(game: string = 'town-star'): Promise<GalaCraftedItem[]> {
return this.client({
method: 'get',
url: `${this.baseUri}/craftable/${game}`,
}).then(response => response.data)
}
}