import {Container} from "../../di" import {Cache} from "../../util" import {CacheModel} from "./CacheModel" /** * A cache driver whose records are stored in a database table using the CacheModel. */ export class ORMCache extends Cache { public async fetch(key: string): Promise { const model = await CacheModel.query() .where(CacheModel.qualifyKey(), '=', key) .where(CacheModel.propertyToColumn('cacheExpires'), '>', new Date()) .first() if ( model ) { return model.cacheValue } } public async put(key: string, value: string, expires?: Date): Promise { let model = await CacheModel.findByKey(key) if ( !model ) { model = Container.getContainer().make(CacheModel) } model.cacheKey = key model.cacheValue = value model.cacheExpires = expires await model.save() } public async has(key: string): Promise { return CacheModel.query() .where(CacheModel.qualifyKey(), '=', key) .where(CacheModel.propertyToColumn('cacheExpires'), '>', new Date()) .exists() } public async drop(key: string): Promise { await CacheModel.query() .where(CacheModel.qualifyKey(), '=', key) .delete() } }