-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.ts
101 lines (87 loc) · 2.4 KB
/
api.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
92
93
94
95
96
97
98
99
100
101
import { createGetTokenRequestFunction } from './common'
import type { Currency, Symbol, CurrencyConversion } from './types'
/**
*
* @export
* @interface GetTokenRequest
*/
export interface GetTokenRequest {
/**
*
* @type {string}
* @memberof GetTokenRequest
*/
symbol: Symbol
/**
*
* @type {string}
* @memberof GetTokenRequest
*/
currency?: Currency
/**
*
* @type {number}
* @memberof GetTokenRequest
*/
quantity?: number
}
/**
* CryptoConverterAPI - object-oriented interface
* @export
* @class CryptoConverterAPI
* @extends {BaseAPI}
*/
export class CryptoConverterAPI {
/**
*
* @summary Get token price in currency
* @param {getTokenPrice} getTokenPrice
* @param {*} [options] Override http request option.
* @throws {Error}
*/
public async getTokenPrice(
{ symbol, currency = 'USD' }: GetTokenRequest,
options?: RequestInit
): Promise<number> {
console.assert(symbol)
const cryptoId = symbol.split(' ').join('-').toLowerCase()
const currencyCode = currency.toLowerCase()
const endpoint = `/coins/${cryptoId}`
const { market_data } = await createGetTokenRequestFunction({ endpoint, options })
const cryptoPrice = market_data.current_price[currencyCode]
if (!cryptoPrice) {
throw new Error("Currency Not Available!");
}
return cryptoPrice;
}
/**
*
* @summary Convert crypto price to currency with quantity
* @param {ConvertToCurrency} ConvertToCurrency
* @param {*} [options] Override http request option.
* @throws {Error}
*/
public async ConvertToCrypto(
{ symbol, currency = 'USD', quantity = 1 }: GetTokenRequest,
options?: RequestInit
): Promise<CurrencyConversion> {
const price = await this.getTokenPrice({ symbol, currency }, options)
const conversion = price * quantity
return { amount: conversion, currency, symbol }
}
/**
*
* @summary Convert crypto price to currency with quantity
* @param {ConvertToCurrency} ConvertToCurrency
* @param {*} [options] Override http request option.
* @throws {Error}
*/
public async ConvertToCurrency(
{ symbol, currency = 'USD', quantity = 1 }: GetTokenRequest,
options?: RequestInit
): Promise<CurrencyConversion> {
const price = await this.getTokenPrice({ symbol, currency }, options)
const conversion = quantity / price
return { amount: conversion, currency, symbol }
}
}