73 lines
2.6 KiB
TypeScript
73 lines
2.6 KiB
TypeScript
|
import {
|
||
|
AbstractFactory,
|
||
|
Container,
|
||
|
DependencyRequirement,
|
||
|
PropertyDependency,
|
||
|
isInstantiable,
|
||
|
DEPENDENCY_KEYS_METADATA_KEY,
|
||
|
DEPENDENCY_KEYS_PROPERTY_METADATA_KEY
|
||
|
} from "@extollo/di"
|
||
|
import {Collection, ErrorWithContext} from "@extollo/util"
|
||
|
import {Logging} from "../../service/Logging";
|
||
|
import {Config} from "../../service/Config";
|
||
|
import {Cache} from "./Cache"
|
||
|
import {MemoryCache} from "./MemoryCache";
|
||
|
|
||
|
export class CacheFactory extends AbstractFactory {
|
||
|
protected readonly logging: Logging
|
||
|
protected readonly config: Config
|
||
|
|
||
|
private static loggedMemoryCacheWarningOnce = false
|
||
|
|
||
|
constructor() {
|
||
|
super({})
|
||
|
this.logging = Container.getContainer().make<Logging>(Logging)
|
||
|
this.config = Container.getContainer().make<Config>(Config)
|
||
|
}
|
||
|
|
||
|
produce(dependencies: any[], parameters: any[]): Cache {
|
||
|
return new (this.getCacheClass())
|
||
|
}
|
||
|
|
||
|
match(something: any) {
|
||
|
return something === Cache
|
||
|
}
|
||
|
|
||
|
getDependencyKeys(): Collection<DependencyRequirement> {
|
||
|
const meta = Reflect.getMetadata(DEPENDENCY_KEYS_METADATA_KEY, this.getCacheClass())
|
||
|
if ( meta ) return meta
|
||
|
return new Collection<DependencyRequirement>()
|
||
|
}
|
||
|
|
||
|
getInjectedProperties(): Collection<PropertyDependency> {
|
||
|
const meta = new Collection<PropertyDependency>()
|
||
|
let currentToken = this.getCacheClass()
|
||
|
|
||
|
do {
|
||
|
const loadedMeta = Reflect.getMetadata(DEPENDENCY_KEYS_PROPERTY_METADATA_KEY, currentToken)
|
||
|
if ( loadedMeta ) meta.concat(loadedMeta)
|
||
|
currentToken = Object.getPrototypeOf(currentToken)
|
||
|
} while (Object.getPrototypeOf(currentToken) !== Function.prototype && Object.getPrototypeOf(currentToken) !== Object.prototype)
|
||
|
|
||
|
return meta
|
||
|
}
|
||
|
|
||
|
protected getCacheClass() {
|
||
|
const CacheClass = this.config.get('server.cache.driver', MemoryCache)
|
||
|
if ( CacheClass === MemoryCache && !CacheFactory.loggedMemoryCacheWarningOnce ) {
|
||
|
this.logging.warn(`You are using the default memory-based cache driver. It is recommended you configure a persistent cache driver instead.`)
|
||
|
CacheFactory.loggedMemoryCacheWarningOnce = true
|
||
|
}
|
||
|
|
||
|
if ( !isInstantiable(CacheClass) || !(CacheClass.prototype instanceof Cache) ) {
|
||
|
const e = new ErrorWithContext('Provided session class does not extend from @extollo/lib.Cache');
|
||
|
e.context = {
|
||
|
config_key: 'server.cache.driver',
|
||
|
class: CacheClass.toString(),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return CacheClass
|
||
|
}
|
||
|
}
|