1 | 'use strict';
|
2 |
|
3 | const fetch = require('node-fetch');
|
4 |
|
5 | const url = 'http://worldtimeapi.org/api/timezone/Etc/UTC';
|
6 |
|
7 | let ip;
|
8 | async 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 |
|
28 | module.exports = globalTime;
|