emoji-picker-element/src/database/Database.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-05-13 05:25:46 +02:00
import { IndexedDBEngine } from './IndexedDBEngine'
import { assertNonEmptyString } from './utils/assertNonEmptyString'
2020-05-17 02:51:37 +02:00
import { assertETag } from './utils/assertETag'
import { assertEmojiBaseData } from './utils/assertEmojiBaseData'
import { assertNumber } from './utils/assertNumber'
2020-05-17 05:36:21 +02:00
import { DEFAULT_DATA_SOURCE, DEFAULT_LOCALE } from './constants'
2020-05-13 05:25:46 +02:00
export class Database {
2020-05-17 02:20:00 +02:00
constructor ({ dataSource = DEFAULT_DATA_SOURCE, locale = DEFAULT_LOCALE } = {}) {
2020-05-13 05:25:46 +02:00
this._dataSource = dataSource
this._locale = locale
this._idbEngine = undefined
this._readyPromise = this._init()
}
async _init () {
2020-05-17 02:20:00 +02:00
this._idbEngine = new IndexedDBEngine(`lite-emoji-picker-${this._locale}`)
await this._idbEngine.open()
if (!(await this._idbEngine.isEmpty())) {
// just do a simple HEAD request first to see if the eTags match
let headResponse
try {
headResponse = await fetch(this._dataSource, { method: 'HEAD' })
} catch (e) {
// offline fallback, just keep current data
console.warn('lite-emoji-picker: falling back to offline mode', e)
return
}
const eTag = headResponse.headers.get('etag')
2020-05-17 02:51:37 +02:00
assertETag(eTag)
2020-05-17 02:20:00 +02:00
if (await this._idbEngine.hasData(this._dataSource, eTag)) {
return // fast init, data is already loaded
}
}
2020-05-13 17:12:56 +02:00
const response = await fetch(this._dataSource)
const emojiBaseData = await response.json()
2020-05-17 02:51:37 +02:00
assertEmojiBaseData(emojiBaseData)
2020-05-17 02:20:00 +02:00
const eTag = response.headers.get('etag')
2020-05-17 02:51:37 +02:00
assertETag(eTag)
2020-05-17 02:20:00 +02:00
await this._idbEngine.loadData(emojiBaseData, this._dataSource, eTag)
2020-05-13 05:25:46 +02:00
}
async getEmojiByGroup (group) {
2020-05-17 02:51:37 +02:00
assertNumber(group)
2020-05-13 05:25:46 +02:00
await this._readyPromise
return this._idbEngine.getEmojiByGroup(group)
}
async getEmojiBySearchPrefix (prefix) {
assertNonEmptyString(prefix)
await this._readyPromise
return this._idbEngine.getEmojiBySearchPrefix(prefix)
}
async getEmojiByShortcode (shortcode) {
assertNonEmptyString(shortcode)
await this._readyPromise
return this._idbEngine.getEmojiByShortcode(shortcode)
}
async getEmojiByUnicode (unicode) {
assertNonEmptyString(unicode)
await this._readyPromise
return this._idbEngine.getEmojiByUnicode(unicode)
}
async close () {
await this._readyPromise
if (this._idbEngine) {
await this._idbEngine.close()
this._idbEngine = undefined
}
}
async delete () {
await this._readyPromise
if (this._idbEngine) {
await this._idbEngine.delete()
this._idbEngine = undefined
}
}
2020-05-17 02:20:00 +02:00
}