-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
121 lines (86 loc) · 3 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
self.addEventListener('load', (e)=>{
currencylist();
})
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then((reg)=>{
console.log('Service worker registered successfully');
}).catch((err)=>{
console.log('Ooops' ,err);
})
}
//fetch currency list from net
const fetchCurr = () =>{
const url = 'https://free.currencyconverterapi.com/api/v5/currencies';
return fetch(url).then(res=>{
return res.json();
})
}
const currConv = (url)=>{
return fetch(url).then(res=>{
return res.json();
})
}
const dbPromise = idb.open('currency-store', 2, upgradeDB => {
switch (upgradeDB.oldVersion) {
case 0:
upgradeDB.createObjectStore('currency-list', {'keyPath' : 'id'});
case 1:
upgradeDB.createObjectStore('my-conversions', {'keyPath' : 'name'});
}
});
//get currency list for user to select
const currencylist = () =>{
let from = document.getElementById('from');
let to = document.getElementById('to');
let currlist;
//fetch from database or from net if its a very first time
dbPromise.then(db =>{
return db.transaction('currency-list','readwrite').objectStore('currency-list').getAll();
}).then(list =>{
if (list.length === 0) {
fetchCurr().then(fetchList =>{
currlist = Object.values(fetchList.results);
dbPromise.then(db =>{
const tx = db.transaction('currency-list','readwrite');
tx.objectStore('currency-list').put(currlist);
return tx.complete;
});
});
}
else{
currlist = list;
}
})
}
//convert currency
const convertCurrency = () => {
let fromCurrency = document.getElementById('from').value;
let toCurrency = document.getElementById('to').value;
let amount = document.getElementById('amount').value;
let result = document.getElementById('result');
fromCurrency = encodeURIComponent(fromCurrency);
toCurrency = encodeURIComponent(toCurrency);
const query = fromCurrency + '_' + toCurrency;
const url = 'https://free.currencyconverterapi.com/api/v5/convert?q='
+ query + '&compact=ultra';
currConv(url).then((jsondata) => {
let val = jsondata[query];
let item = {
name: `'${query}'`,
rate: val
}
dbPromise.then(db =>{
return db.transaction('my-conversions', 'readwrite')
.objectStore('my-conversions').put(item);
})
if (val != undefined) {
let total = parseFloat(val) * parseFloat(amount);
if (total !== NaN) {
result.value = total;
}
} else {
var err = new Error("Value not found for " + query);
console.log(err);
}
})
}