@yura_born

Как работать с IndexedDB из класса?

Всем привет! разбираюсь с IndexedDB с толкнулся с такой проблемой.
Сначала я тестил код из примера:
let openRequest = indexedDB.open('yura-yushkevich', 1);
let db;

openRequest.onupgradeneeded = function() {
    db = openRequest.result;
    db.createObjectStore('books', {autoIncrement: 'true'});    
  };
  
  openRequest.onerror = function() {
    console.error("Error", openRequest.error);
  };
  
  openRequest.onsuccess = function() {
    db = openRequest.result;    

    db.onversionchange = function() {
      db.close();
      alert("База данных устарела, пожалуста, перезагрузите страницу.")
    };
  };

function addBook(){
    let transaction = db.transaction("books", "readwrite"); // (1)

    // получить хранилище объектов для работы с ним
    let books = transaction.objectStore("books"); // (2)

    let book = {
    id: 'js',
    price: 10,
    created: new Date()
    };

    let request = books.add(book); // (3)

    request.onsuccess = function() { // (4)
    console.log("Книга добавлена в хранилище", request.result);
    };

    request.onerror = function() {
    console.log("Ошибка", request.error);
    };
}

Все отрабатывает отлично, но у меня проект на TypeScript и я решил закинуть все в класс, др. решения не нашел.... вот что получилось:
export class IndexDBMatch {
  openRequest: IDBOpenDBRequest | null = null;

  db: IDBDatabase | null = null;

  constructor(readonly DBName: string, readonly bdTableName: string, readonly DBVersion: number) {
    this.DBName = DBName;
    this.DBVersion = DBVersion;
    this.OpenInitDB(bdTableName);
  }

  OpenInitDB(table: string): void {
    this.openRequest = indexedDB.open(this.DBName, this.DBVersion);

    this.openRequest.onupgradeneeded = () => {
      if (this.openRequest !== null) {
        this.db = this.openRequest.result;
        if (this.db !== null) {
          // const inventory = this.db.createObjectStore(table, { autoIncrement: true });
          const inventory = this.db.createObjectStore(table, { keyPath: 'id', autoIncrement: true });
          inventory.createIndex('active_idx', 'active');
        }
      }
    };

    // this.openRequest.onsuccess = () => {
    //   console.log(`Из onsuccess - ${this.db}`);
    //   if (this.openRequest !== null) {
    //     this.db = this.openRequest.result;
    //   }
    // };

    this.openRequest.onerror = () => {
      if (this.openRequest !== null) {
        console.error('Error', this.openRequest.error);
      }
    };

    if (this.db !== null) {
      this.db.onversionchange = () => {
        if (this.db !== null) {
          this.db.close();
        }
        alert('База данных устарела, пожалуйста, перезагрузите страницу.');
      };
    }
  }

  Add(bdTableName: string, record: User): void {
    let transaction: IDBTransaction | null = null;
    let objTable: IDBObjectStore | null = null;
    let request: IDBRequest<IDBValidKey> | null = null;

    if (this.db !== null) {
      transaction = this.db.transaction(bdTableName, 'readwrite');
    }

    if (transaction !== null) {
      objTable = transaction.objectStore(bdTableName);
    }

    if (objTable !== null) {
      request = objTable.put(record);
    }

    if (request !== null) {
      request.onsuccess = () => {
        if (request !== null) {
          console.log(`Запись добавлена в таблицу ${request.result}`);
        }
      };

      request.onerror = () => {
        if (request !== null) {
          console.log('Ошибка', request.error);
        }
      };
    }
  }

  getRecord(bdTableName: string, findFild: string, findValue: string | number): IDBRequest {
    if (!this.db) throw Error('this.db in getRecord() is null');
    const transaction = this.db.transaction(bdTableName);

    const objTable = transaction.objectStore(bdTableName);
    const findFieldIndex = objTable.index(findFild);
    const request = findFieldIndex.get(findValue);
    // request = objTable.get(findValue);

    if (request !== null) {
      request.onsuccess = () => {
        if (request !== null) {
          console.log(`Запись найдена ${request.result}`);
        }
      };
    }

    request.onerror = () => {
      console.log('Ошибка', request.error);
    };

    return request;
  }

  getActiveUser() {
    let result: User;
    if (!this.openRequest) throw Error('Error openRequest in func getActiveUser is null!');
    this.openRequest.onsuccess = () => {
      if (!this.openRequest) throw Error('Error openRequest in func getActiveUser is null!');
      const db = this.openRequest.result;
      const transaction = db.transaction('users', 'readwrite');
      const objTable = transaction.objectStore('users');
      const findFieldIndex = objTable.index('active_idx');
      const request = findFieldIndex.get('active');
      console.log(request);
      // request = objTable.get(findValue);

      if (request !== null) {
        request.onsuccess = (e: Event) => {
          if (request !== null) {
            console.log(`Запись найдена ${request.result}`);
            if (!e.target) throw Error('Error target');
            result = request.result;
          }
        };
      }

      request.onerror = () => {
        console.log('Ошибка', request.error);
      };

      return result;
    };
  }
}


и вот тут у меня проблема я никак не могу получить значение из 'onsuccess' например из метода getActiveUser(), помогите, как сделать, может я вообще не в том направлении? 3-ий день в муках :)
  • Вопрос задан
  • 193 просмотра
Пригласить эксперта
Ответы на вопрос 1
bingo347
@bingo347 Куратор тега JavaScript
Crazy on performance...
https://developer.mozilla.org/ru/docs/Web/JavaScri...
100 раз уже это спрашивали...
Научитесь работать с асинхронным кодом...
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы