UNPKG

symspell-ex

Version:

Spelling correction & Fuzzy search based on symmetric delete spelling correction algorithm

93 lines (92 loc) 3.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RedisStore = void 0; const core_1 = require("../core"); const MAX_ENTRY_LENGTH = 'maxEntryLength'; class RedisStore { constructor(instance) { this.name = 'redis_store'; this._language = core_1.Languages.ENGLISH; this._MAIN_KEY = 'symspell_ex'; this._CONFIG_KEY = 'config'; this._TERMS_KEY = 'terms'; this._ENTRIES_KEY = 'entries'; this._initialized = false; this._termsCount = 0; this._redis = instance; } async initialize() { await this._redis.defineCommand('hSetEntry', { numberOfKeys: 2, lua: ` local olen = redis.call("hget", "${this._configNamespace}", ARGV[2]) local value = redis.call("hset", KEYS[1], KEYS[2], ARGV[1]) local nlen = #KEYS[2] if(not olen or nlen > tonumber(olen)) then redis.call("hset", "${this._configNamespace}", ARGV[2], nlen) end return value ` }); this._initialized = true; } isInitialized() { return this._initialized; } get _configNamespace() { return `${this._MAIN_KEY}:${this._CONFIG_KEY}`; } get _termsNamespace() { return `${this._MAIN_KEY}:${this._language}:${this._TERMS_KEY}`; } get _entriesNamespace() { return `${this._MAIN_KEY}:${this._language}:${this._ENTRIES_KEY}`; } get _maxEntryLength() { return `${this._language}.${MAX_ENTRY_LENGTH}`; } async setLanguage(language) { this._language = language; this._termsCount = await this._redis.hlen(this._termsNamespace); } async pushTerm(value) { const key = (this._termsCount++).toString(); await this._redis.hset(this._termsNamespace, key, value); return this._termsCount; } async getTermAt(index) { return this._redis.hget(this._termsNamespace, index.toString()); } async getTermsAt(indexes) { const keys = indexes.map((i) => i.toString()); return this._redis.hmget(this._termsNamespace, ...keys); } async setEntry(key, value) { const mValue = JSON.stringify(value); return this._redis.hSetEntry(this._entriesNamespace, key, mValue, this._maxEntryLength) .then((value) => value === 1); } async getEntry(key) { return this._redis.hget(this._entriesNamespace, key) .then((value) => JSON.parse(value)); } async getEntries(keys) { return this._redis.hmget(this._entriesNamespace, ...keys) .then((values) => values.map((value) => JSON.parse(value))); } async hasEntry(key) { return this._redis.hexists(this._entriesNamespace, key) .then((value) => value === 1); } async maxEntryLength() { return this._redis.hget(this._configNamespace, this._maxEntryLength) .then((value) => parseInt(value)); } async clear() { const keys = await this._redis.keys(`${this._MAIN_KEY}:*`); for (let i = 0; i < keys.length; i += 1) { await this._redis.del(keys[i]); } } } exports.RedisStore = RedisStore;