1 | 'use strict';
|
2 |
|
3 | const fetch = require('node-fetch');
|
4 |
|
5 | const url = 'http://worldtimeapi.org/api/timezone/Etc/UTC';
|
6 | let ip;
|
7 |
|
8 | async function globalTime() {
|
9 | let obj;
|
10 | try {
|
11 | obj = await fetch(url).then(e => e.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 | }
|
18 | throw e;
|
19 | }
|
20 | ip = obj.client_ip;
|
21 |
|
22 | const [, tail = ''] = obj.utc_datetime.match(/:\d+.\d{3}(\d*)\+/) || [];
|
23 | const time = +`${+new Date(obj.utc_datetime)}.${tail}`;
|
24 | return time;
|
25 | }
|
26 |
|
27 | module.exports = globalTime;
|