This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/matrix/storage/idb/StorageFactory.js

60 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-08-05 22:08:55 +05:30
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import {Storage} from "./Storage.js";
2019-10-13 00:46:48 +05:30
import { openDatabase, reqAsPromise } from "./utils.js";
2019-12-14 22:59:35 +05:30
import { exportSession, importSession } from "./export.js";
2020-06-27 02:56:24 +05:30
import { schema } from "./schema.js";
2019-12-14 22:59:35 +05:30
const sessionName = sessionId => `hydrogen_session_${sessionId}`;
2020-06-27 02:56:24 +05:30
const openDatabaseWithSessionId = sessionId => openDatabase(sessionName(sessionId), createStores, schema.length);
2019-02-07 03:34:39 +05:30
export class StorageFactory {
constructor(serviceWorkerHandler) {
this._serviceWorkerHandler = serviceWorkerHandler;
}
2019-10-13 00:46:48 +05:30
async create(sessionId) {
await this._serviceWorkerHandler?.preventConcurrentSessionAccess(sessionId);
2019-12-14 22:59:35 +05:30
const db = await openDatabaseWithSessionId(sessionId);
2019-10-13 00:46:48 +05:30
return new Storage(db);
}
delete(sessionId) {
2019-12-14 22:59:35 +05:30
const databaseName = sessionName(sessionId);
2020-09-28 18:22:12 +05:30
const req = indexedDB.deleteDatabase(databaseName);
2019-10-13 00:46:48 +05:30
return reqAsPromise(req);
}
2019-12-14 22:59:35 +05:30
async export(sessionId) {
const db = await openDatabaseWithSessionId(sessionId);
return await exportSession(db);
}
async import(sessionId, data) {
const db = await openDatabaseWithSessionId(sessionId);
return await importSession(db, data);
}
2019-02-05 04:51:50 +05:30
}
2020-06-27 02:56:24 +05:30
async function createStores(db, txn, oldVersion, version) {
const startIdx = oldVersion || 0;
2019-04-18 23:49:43 +05:30
2020-06-27 02:56:24 +05:30
for(let i = startIdx; i < version; ++i) {
await schema[i](db, txn);
}
2019-04-18 23:49:43 +05:30
}