Import other modules into monorepo
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
33
src/util/cache/Cache.ts
vendored
Normal file
33
src/util/cache/Cache.ts
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
import {Awaitable} from "../support/types"
|
||||
|
||||
/**
|
||||
* Abstract interface class for a cached object.
|
||||
*/
|
||||
export abstract class Cache {
|
||||
/**
|
||||
* Fetch a value from the cache by its key.
|
||||
* @param {string} key
|
||||
* @return Promise<any|undefined>
|
||||
*/
|
||||
public abstract fetch(key: string): Awaitable<string|undefined>;
|
||||
|
||||
/**
|
||||
* Store the given value in the cache by key.
|
||||
* @param {string} key
|
||||
* @param {string} value
|
||||
*/
|
||||
public abstract put(key: string, value: string): Awaitable<void>;
|
||||
|
||||
/**
|
||||
* Check if the cache has the given key.
|
||||
* @param {string} key
|
||||
* @return Promise<boolean>
|
||||
*/
|
||||
public abstract has(key: string): Awaitable<boolean>;
|
||||
|
||||
/**
|
||||
* Drop the given key from the cache.
|
||||
* @param {string} key
|
||||
*/
|
||||
public abstract drop(key: string): Awaitable<void>;
|
||||
}
|
||||
41
src/util/cache/InMemCache.ts
vendored
Normal file
41
src/util/cache/InMemCache.ts
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Cache } from './Cache'
|
||||
import { Collection } from '../collection/Collection'
|
||||
|
||||
/**
|
||||
* Base interface for an item stored in a memory cache.
|
||||
*/
|
||||
export interface InMemCacheItem {
|
||||
key: string,
|
||||
item: string,
|
||||
}
|
||||
|
||||
/**
|
||||
* A cache implementation stored in memory.
|
||||
* @extends Cache
|
||||
*/
|
||||
export class InMemCache extends Cache {
|
||||
/**
|
||||
* The stored cache items.
|
||||
* @type Collection<InMemCacheItem>
|
||||
*/
|
||||
protected items: Collection<InMemCacheItem> = new Collection<InMemCacheItem>()
|
||||
|
||||
public async fetch(key: string) {
|
||||
const item = this.items.firstWhere('key', '=', key)
|
||||
if ( item ) return item.item
|
||||
}
|
||||
|
||||
public async put(key: string, item: string) {
|
||||
const existing = this.items.firstWhere('key', '=', key)
|
||||
if ( existing ) existing.item = item
|
||||
else this.items.push({ key, item })
|
||||
}
|
||||
|
||||
public async has(key: string) {
|
||||
return this.items.where('key', '=', key).length > 0
|
||||
}
|
||||
|
||||
public async drop(key: string) {
|
||||
this.items = this.items.whereNot('key', '=', key)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user