UNPKG

741 BJavaScriptView Raw
1'use strict';
2
3const fetch = require('node-fetch');
4
5const url = 'http://worldtimeapi.org/api/timezone/Etc/UTC';
6
7let ip;
8async function globalTime() {
9 let obj;
10 try {
11 obj = await (await fetch(url)).json();
12 } catch(e) {
13 if(e.code === 'ENOTFOUND') {
14 throw new Error(`"${url}" is currently unavailable.`);
15 } else if(e.type === 'invalid-json') {
16 throw new Error(`Too many requests for "${url}"${ip ? ` from ip "${ip}"` : ''}. Try a bit later.`);
17 } else {
18 throw e;
19 }
20 }
21 ip = obj.client_ip;
22
23 const tail = (obj.utc_datetime.match(/:\d+.\d{3}(\d*)\+/) || [, ''])[1];
24 const time = +`${+new Date(obj.utc_datetime)}.${tail}`;
25 return time;
26}
27
28module.exports = globalTime;