aboutsummaryrefslogtreecommitdiff
path: root/src/zenserver/frontend/html/indexer/cache.js
blob: b90194855c985a173e6bc8232e851a0402b69c5c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright Epic Games, Inc. All Rights Reserved.

"use strict";

////////////////////////////////////////////////////////////////////////////////
export class Cache
{
	constructor(db_name, ...store_names)
	{
		this._db_name = db_name;
		this._store_names = store_names;
		this._version = 2;
		this._db = this._open();
	}

	put(store_name, key, value)
	{
		const executor = async (resolve, reject) => {
			const db = await this._db;
			const transaction = db.transaction(store_name, "readwrite");
			const store = transaction.objectStore(store_name);
			const request = store.put(value, key);
			request.onerror = (evt) => reject(Error("put transaction error"));
			request.onsuccess = (evt) => resolve(true);
		};
		return new Promise(executor);
	}

	get(store_name, key)
	{
		const executor = async (resolve, reject) => {
			const db = await this._db;
			const transaction = db.transaction(store_name, "readonly");
			const store = transaction.objectStore(store_name);
			const request = store.get(key);
			request.onerror = (evt) => reject(Error("get transaction error"));
			request.onsuccess = (evt) => {
				if (request.result)
					resolve(request.result);
				else
					resolve(false);
			};
		};
		return new Promise(executor);
	}

	_open()
	{
		const executor = (resolve, reject) => {
			const request = indexedDB.open(this._db_name, this._version);
			request.onerror = (evt) => reject(Error("Failed to open IndexedDb"));
			request.onsuccess = (evt) => resolve(evt.target.result);
			request.onupgradeneeded = (evt) => {
				const db = evt.target.result;

				for (const store_name of db.objectStoreNames)
					db.deleteObjectStore(store_name)

				for (const store_name of this._store_names)
					db.createObjectStore(store_name);
			};
		};
		return new Promise(executor);
	}
}