-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcrypto.js
79 lines (75 loc) · 2.08 KB
/
crypto.js
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
import axios from 'axios'
import _isEmpty from 'lodash/isEmpty'
import store from '../ext/storage'
import config from '../utils/config'
import debug from '../utils/debug'
const SETTING_DB_NAME = 'settings'
const API_URL = {
default: (limit = 10) => {
return { limit }
},
all: {limit: '500'},
coinMarket: `https://api.coinmarketcap.com/v1/ticker/?`,
convert: ''
}
const checkCache = (key) => {
let date2 = new Date()
const cached = store.lget(key)
if (cached && cached.createdAt && Math.abs(date2.getTime() - new Date(cached.createdAt).getTime()) < config.CACHE_TIME) {
return new Promise((resolve, reject) => {
debug.log(`Cached : ${key}`)
resolve(cached)
})
} else {
debug.log('NON cached')
return null
}
}
const cacheAPI = {
paramsStr (data) {
let result = data
let currentCurrency = API_URL.convert
if (currentCurrency !== '') {
result = {
...result,
currentCurrency
}
}
return new Promise((resolve, reject) => {
store.get(SETTING_DB_NAME)
.then((db) => {
if (!_isEmpty(db[SETTING_DB_NAME])) {
if (db[SETTING_DB_NAME].currentCurrency && db[SETTING_DB_NAME].currentCurrency.value !== 'USD') {
result.convert = db[SETTING_DB_NAME].currentCurrency.value
}
}
resolve(Object.keys(result).map(key => `${key}=${encodeURIComponent(result[key])}`).join('&'))
})
})
},
async call (path, param) {
let paramPath = path + await this.paramsStr(param)
const cache = checkCache(paramPath)
if (cache) {
return cache
} else {
return axios.get(paramPath).then(response => {
response['createdAt'] = new Date()
store.lset(paramPath, response)
return new Promise((resolve, reject) => {
resolve(response)
})
})
}
}
}
export default {
getAllCryptoPrice () {
const param = API_URL.all
return cacheAPI.call(API_URL.coinMarket, param)
},
getCryptoPrice () {
const param = API_URL.default()
return cacheAPI.call(API_URL.coinMarket, param)
}
}