forked from nicholasfoden/rocketchat-cryptoconvert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CryptocompareAPI.ts
91 lines (72 loc) · 2.75 KB
/
CryptocompareAPI.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { IHttp, IModify, IPersistence, IRead, IHttpRequest, HttpStatusCode } from '@rocket.chat/apps-engine/definition/accessors';
import { ISettingRead } from "@rocket.chat/apps-engine/definition/accessors/";
import { CryptoVertStrings } from "./CryptoVertStrings";
export class CryptocompareAPI {
//TODO add option for different API's
private readonly url: string = 'https://min-api.cryptocompare.com/data/';
constructor(private key: string = ""){
this.setKey(key);
}
public setKey(key): void {
this.key = key;
}
public async getAllCoins(http: IHttp) {
let options = { headers: { authorization: 'Apikey ' + this.key }};
const result = await http.get(this.url + 'all/coinlist', options);
if(result.statusCode == HttpStatusCode.OK && result.content){
return Object.values(JSON.parse(result.content).Data).map((coin: any) => coin.Symbol);
}
else {
throw new Error(CryptoVertStrings.FAILED_FETCH);
}
}
/**
* Gets a price from the API for a given conversion
* @returns Object An object containing the price for the symbols requested e.g. `{ USD: 123.45 }`
*/
public async getPrice(
http: IHttp,
from: string,
to: string
): Promise<any> {
// Create options for the request
let options = {
headers: { authorization: 'Apikey ' + this.key },
params: { fsym: from, tsyms: to }
}
// Fetch the results from the API
const result = await http.get(this.url + 'price', options);
// Check we have a proper response
if (result.statusCode === HttpStatusCode.OK && result.data) {
// console.log("result " + JSON.stringify(result));
return result.data;
} else {
// console.log("error " + JSON.stringify(result));
throw new Error(CryptoVertStrings.FAILED_FETCH);
}
}
public async getPrices(
http: IHttp,
from: string,
to: Array<string>
): Promise<any> {
// Create options for the request
let options = {
headers: { authorization: 'Apikey ' + this.key },
params: {
fsym: from,
tsyms: to.map(sym => sym.toUpperCase()).reduce((acc, current) => acc.concat(current + ","), "")
}
}
// Fetch the results from the API
const result = await http.get(this.url + 'price', options);
// Check we have a proper response
if (result.statusCode === HttpStatusCode.OK && result.data) {
// console.log("result " + JSON.stringify(result.data));
return result.data;
} else {
// console.log("error " + JSON.stringify(result));
throw new Error(CryptoVertStrings.FAILED_FETCH);
}
}
}