Cache manifest json files (#104)

* Add cache code

* Fix typo and add cache option to documentation

* Match logging style

* Add return

* Follow ESLint style guide

* Support older Node Versions
This commit is contained in:
TehMartinXz 2023-03-10 18:36:33 -03:00 committed by GitHub
parent 0e4218b36a
commit 1fa4668de9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 5 deletions

View file

@ -112,18 +112,44 @@ class Handler {
}
const manifest = `${this.options.overrides.url.meta}/mc/game/version_manifest.json`
const cache = this.options.cache ? `${this.options.cache}/json` : `${this.options.root}/cache/json`
request.get(manifest, (error, response, body) => {
if (error) return resolve(error)
if (error && error.code !== 'ENOTFOUND') return resolve(error)
if (!error) {
if (!fs.existsSync(cache)) {
fs.mkdirSync(cache, { recursive: true })
this.client.emit('debug', '[MCLC]: Cache directory created.')
}
fs.writeFile(path.join(`${cache}/version_manifest.json`), body, (err) => {
if (err) return resolve(err)
this.client.emit('debug', '[MCLC]: Cached version_manifest.json')
})
}
const parsed = JSON.parse(body)
let parsed
if (error && (error.code === 'ENOTFOUND')) {
parsed = JSON.parse(fs.readFileSync(`${cache}/version_manifest.json`))
} else {
parsed = JSON.parse(body)
}
for (const desiredVersion in parsed.versions) {
if (parsed.versions[desiredVersion].id === this.options.version.number) {
request.get(parsed.versions[desiredVersion].url, (error, response, body) => {
if (error) return resolve(error)
if (error && error.code !== 'ENOTFOUND') return resolve(error)
if (!error) {
fs.writeFile(path.join(`${cache}/${this.options.version.number}.json`), body, (err) => {
if (err) return resolve(err)
this.client.emit('debug', `[MCLC]: Cached ${this.options.version.number}.json`)
})
}
this.client.emit('debug', '[MCLC]: Parsed version from version manifest')
this.version = JSON.parse(body)
if (error && (error.code === 'ENOTFOUND')) {
this.version = JSON.parse(fs.readFileSync(`${cache}/${this.options.version.number}.json`))
} else {
this.version = JSON.parse(body)
}
return resolve(this.version)
})
}