You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.4 KiB
46 lines
1.4 KiB
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<string | undefined> {
|
|
const model = await CacheModel.query<CacheModel>()
|
|
.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<void> {
|
|
let model = await CacheModel.findByKey<CacheModel>(key)
|
|
if ( !model ) {
|
|
model = <CacheModel> Container.getContainer().make(CacheModel)
|
|
}
|
|
|
|
model.cacheKey = key
|
|
model.cacheValue = value
|
|
model.cacheExpires = expires
|
|
|
|
await model.save()
|
|
}
|
|
|
|
public async has(key: string): Promise<boolean> {
|
|
return CacheModel.query()
|
|
.where(CacheModel.qualifyKey(), '=', key)
|
|
.where(CacheModel.propertyToColumn('cacheExpires'), '>', new Date())
|
|
.exists()
|
|
}
|
|
|
|
public async drop(key: string): Promise<void> {
|
|
await CacheModel.query()
|
|
.where(CacheModel.qualifyKey(), '=', key)
|
|
.delete()
|
|
}
|
|
}
|