ts-cache-mongoose
Version:
Cache plugin for mongoose Queries and Aggregate (in-memory, redis)
115 lines (110 loc) • 3.02 kB
JavaScript
;
var common = require('@nestjs/common');
var mongoose = require('mongoose');
var index = require('../index.cjs');
require('node:v8');
require('bson');
require('ioredis');
require('node:crypto');
const CACHE_OPTIONS = Symbol("CACHE_OPTIONS");
class CacheService {
logger = new common.Logger(CacheService.name);
options;
cacheMongoose;
constructor(options) {
this.options = options;
}
get instance() {
return this.cacheMongoose;
}
async onApplicationBootstrap() {
this.cacheMongoose = index.init(mongoose, this.options);
this.logger.log(`Cache initialized with ${this.options.engine} engine`);
}
async onApplicationShutdown() {
if (this.cacheMongoose) {
await this.cacheMongoose.close();
}
}
async clear(customKey) {
await this.cacheMongoose.clear(customKey);
}
}
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i = decorators.length - 1, decorator; i >= 0; i--)
if (decorator = decorators[i])
result = (decorator(result)) || result;
return result;
};
exports.CacheModule = class CacheModule {
static forRoot(options) {
return {
module: exports.CacheModule,
global: options.isGlobal ?? false,
providers: [
{ provide: CACHE_OPTIONS, useValue: options },
{
provide: CacheService,
useFactory: (opts) => new CacheService(opts),
inject: [CACHE_OPTIONS]
}
],
exports: [CacheService]
};
}
static forRootAsync(options) {
const asyncProviders = exports.CacheModule.createAsyncProviders(options);
return {
module: exports.CacheModule,
global: options.isGlobal ?? false,
imports: options.imports ?? [],
providers: [
...asyncProviders,
{
provide: CacheService,
useFactory: (opts) => new CacheService(opts),
inject: [CACHE_OPTIONS]
}
],
exports: [CacheService]
};
}
static createAsyncProviders(options) {
if (options.useFactory) {
return [
{
provide: CACHE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject ?? []
}
];
}
if (options.useClass) {
return [
{ provide: options.useClass, useClass: options.useClass },
{
provide: CACHE_OPTIONS,
useFactory: (factory) => factory.createCacheOptions(),
inject: [options.useClass]
}
];
}
if (options.useExisting) {
return [
{
provide: CACHE_OPTIONS,
useFactory: (factory) => factory.createCacheOptions(),
inject: [options.useExisting]
}
];
}
return [];
}
};
exports.CacheModule = __decorateClass([
common.Module({})
], exports.CacheModule);
exports.CACHE_OPTIONS = CACHE_OPTIONS;
exports.CacheService = CacheService;