Skip to content

Commit 7888e69

Browse files
author
Dmitry Shirokov
authored
Merge pull request #41 from runk/check-last-modified
feat: Skip download new databases if existing are up to date
2 parents a7de6c0 + 4293cf9 commit 7888e69

File tree

1 file changed

+46
-9
lines changed

1 file changed

+46
-9
lines changed

scripts/postinstall.js

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,29 +36,66 @@ const link = (edition) =>
3636
`https://download.maxmind.com/app/geoip_download?edition_id=${edition}&license_key=${licenseKey}&suffix=tar.gz`;
3737

3838
const selected = getSelectedDbs();
39-
const links = ['City', 'Country', 'ASN']
39+
const editionIds = ['City', 'Country', 'ASN']
4040
.filter((e) => selected.includes(e))
41-
.map((e) => link(`GeoLite2-${e}`));
41+
.map((e) => `GeoLite2-${e}`);
4242

4343
const downloadPath = path.join(__dirname, '..', 'dbs');
4444

4545
if (!fs.existsSync(downloadPath)) fs.mkdirSync(downloadPath);
4646

4747
const download = (url) =>
4848
new Promise((resolve) => {
49-
https.get(url, function (response) {
49+
https.get(url, (response) => {
5050
resolve(response.pipe(zlib.createGunzip({})));
5151
});
5252
});
5353

54-
console.log('Downloading maxmind databases...');
55-
links.forEach((url) =>
56-
download(url).then((result) =>
54+
// https://dev.maxmind.com/geoip/updating-databases?lang=en#checking-for-the-latest-release-date
55+
const isOutdated = async (dbPath, url) => {
56+
if (!fs.existsSync(dbPath)) return true;
57+
58+
const remoteLastModified = await new Promise((resolve, reject) => {
59+
https
60+
.request(url, { method: 'HEAD' }, (res) =>
61+
resolve(Date.parse(res.headers['last-modified']))
62+
)
63+
.on('error', (err) => reject(err))
64+
.end();
65+
});
66+
const localLastModified = fs.statSync(dbPath).mtimeMs;
67+
68+
return localLastModified < remoteLastModified;
69+
};
70+
71+
const main = async () => {
72+
console.log('Downloading maxmind databases...');
73+
for (const editionId of editionIds) {
74+
const dbPath = path.join(downloadPath, `${editionId}.mmdb`);
75+
const isOutdatedStatus = await isOutdated(dbPath, link(editionId));
76+
77+
if (!isOutdatedStatus) {
78+
console.log(' > %s: Is up to date, skipping download', editionId);
79+
continue;
80+
}
81+
console.log(' > %s: Is either missing or outdated, downloading', editionId);
82+
83+
const result = await download(link(editionId));
5784
result.pipe(tar.t()).on('entry', (entry) => {
5885
if (entry.path.endsWith('.mmdb')) {
5986
const dstFilename = path.join(downloadPath, path.basename(entry.path));
6087
entry.pipe(fs.createWriteStream(dstFilename));
88+
entry.on('end', () => {});
6189
}
62-
})
63-
)
64-
);
90+
});
91+
}
92+
};
93+
94+
main()
95+
.then(() => {
96+
// success
97+
})
98+
.catch((err) => {
99+
console.error(err);
100+
process.exit(1);
101+
});

0 commit comments

Comments
 (0)