Caching return value from a service method - node.js

I am using nestjs and have just installed the cache-manager module and are trying to cache a response from a service call.
I register the cache module in a sample module (sample.module.ts):
import { CacheInterceptor, CacheModule, Module } from '#nestjs/common';
import { SampleService } from './sample.service';
import { APP_INTERCEPTOR } from '#nestjs/core';
import * as redisStore from 'cache-manager-redis-store';
#Module({
imports: [
CacheModule.register({
ttl: 10,
store: redisStore,
host: 'localhost',
port: 6379,
}),
],
providers: [
SampleService,
{
provide: APP_INTERCEPTOR,
useClass: CacheInterceptor,
}
],
exports: [SampleService],
})
export class SampleModule {}
Then in my service (sample.service.ts):
#Injectable()
export class SampleService {
#UseInterceptors(CacheInterceptor)
#CacheKey('findAll')
async findAll() {
// Make external API call
}
}
Looking at redis I can see that nothing is cached for the service method call. If I use the same approach with a controller, then everything works fine and I can see the cached entry in my redis database. I am thinking that there is no way out of the box to cache individual service method calls in nestjs.
Reading the documentation it seems that I am only able to use this approach for controllers, microservices and websockets, but not ordinary services?

Correct, it is not possible to use the cache the same way for services as for controllers.
This is because the magic happens in the CacheInterceptor and Interceptors can only be used in Controllers.
However, you can inject the cacheManager into your service and use it directly:
export class SampleService {
constructor(#Inject(CACHE_MANAGER) protected readonly cacheManager) {}
findAll() {
const value = await this.cacheManager.get(key)
if (value) {
return value
}
const respone = // ...
this.cacheManager.set(key, response, ttl)
return response
}

Related

How to inject Cache Manager in My Custom Provider

I try to use cache-manager in my nestjs web app.
In my Module I register my Cache
#Module({
imports: [
_CacheModule.register(),
],
})
export class CacheModule {}
From the same mudule I have another custom provider which need to inject CacheManager.
import {Cache} from '#nestjs/common'
...
async function providerFactory(
config: Config,
cache: Cache,
logger: Logger,
): Promise<Store> {
return process.env.NODE_ENV === 'development'
? new StoreA(keyValueConfig, cache, logger)
: new StoreB(keyValueConfig, logger);
}
export const RedisOrMockKeyValueStoreProvider: Provider = {
provide: Store,
useFactory: providerFactory,
inject: [Config, Cache, Logger],
};
But I got Cache is not defined Error when the app start. How should I inject the cache into my custom provider?
You should use the CACHE_MANAGER injection token instead of Cache

How to use NestJS Versioning with Router module

In our nest 8 project we use the RouterModule for routing between different parts of the app:
#Module({
imports: [
RouterModule.register([
{
path: '/internal',
module: InternalModule
},
{
path: '/external',
module: ExternalModule
}
]),
],
})
export class AppModule {}
In the InternalModule we would like to use NestJS versioning:
#Controller('someroute')
export class InternalController {
#Get(':id')
#Version(['1'])
async getPerson(#Param('id') id): Promise<any> {}
}
Routing without versioning works, versioning without routing too, but the combination does not.
I tried calling it via "localhost:port/v1/internal/someroute" and "localhost:port/internal/v1/someroute"
Versioning is enabled:
app.enableVersioning({
type: VersioningType.URI
});

NestJS guard with GraphQL

I am trying to add an auth guard to a GraphQL resolver but it doesn't seem to be working as expected.
I have a simple guard that should reject all requests:
#Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
return false;
}
}
and have applied it in a resolver:
#Resolver()
export class RecipeResolver {
#Query(() => [Recipe])
#UseGuards(AuthGuard)
public recipes(): Recipe[] {
return this.recipeData;
}
}
This does not work in the resolver and the canActivate is never fired. This does work in an HTTP Controller.
Changing #UseGuards(AuthGuard) to #UseGuards(new AuthGuard()) works but will not go through the dependency injection process which is not ideal.
What am I doing wrong?
Edit:
original app.module.ts:
#Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: 'shcema.gql',
playground: true,
}),
RecipeResolver,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
From the code, the resolver was in the wrong location (in an imports array instead of providers) which meant Nest didn't set up the request lifecycle properly.

Nestjs - connect bull-board in a normal controller

I created an app using nest.js and bull.
I added bull-board package to monitor my queues, but in documentation, only one way to add it to the app is mount as middleware:
In main.ts:
app.use('/admin/queues', bullUI);
Is there any way to add bullUI in a normal nest controller, after jwt auth? Like:
#UseGuards(JwtAuthGuard)
#Get("queues")
activate() {
return UI
}
You can use any express middleware like this inside controllers, but maybe some cases cause errors like serving static files with Guard exception and etc.
#UseGuards(JwtAuthGuard)
#Get("queues/*")
activate(#Req() req, #Res() res) {
bullUI(req, res)
}
I've got this working via a middleware consumer, so something like this:
import { router } from 'bull-board';
#Module({
imports: [
NestBullModule.forRoot({ redis }),
],
providers: [],
})
export class BullModule {
configure(consumer: MiddlewareConsumer): void {
consumer
.apply(router)
.forRoutes('/admin/queues');
}
}
I'd like to extend the original answer of #JCF, mainly, because it's working and much easier to understand.
I am using not default bull, with #nestjs/queue, but an improved version of BullMQ from anchan828 repo, with NestJS decorators, but I guess in both cases, the result will be the same.
The queue.module file:
#Module({
imports: [
BullModule.forRoot({
options: {
connection: {
host: redisConfig.host,
port: redisConfig.port,
},
},
}),
/** DI all your queues and Redis connection */
BullModule.registerQueue('yourQueueName'),
],
controllers: [],
providers: [],
})
export class QueueModule {
constructor (
#BullQueueInject('yourQueueName')
private readonly queueOne: Queue,
) {
/** Add queues with adapter, one-by-one */
setQueues([new BullMQAdapter(this.queueOne, { readOnlyMode: false })])
}
configure(consumer: MiddlewareConsumer): void {
consumer
.apply(router)
.forRoutes('/admin/queues');
}
}
Then just add it, to parent AppModule, via import, like that:
I am not sure, that Redis connection is needed here, for parent AppModule
#Module({
imports: [
BullModule.forRoot({
options: {
connection: {
host: redisConfig.host,
port: redisConfig.port,
},
},
}),
QueueModule
],
controllers: [],
providers: [],
})
export class AppModule {}
run the main.js, and visit, localhost:8000/admin/queues

Using multiple sockets adapters with NestJS

I'm working on an Node.js application with NestJS. I need to communicate with 2 other apps.
The first one over WebSockets (Socket.io) and the other one over TCP sockets with net module.
Is it possible to use two gateways with specific adapters, one based on Socket.io and the other one on Net module, or do I have to split this application?
You don't need to split the application.
You can define your module as:
#Module({
providers: [
MyGateway,
MyService,
],
})
export class MyModule {}
with the gateway being in charge of the web sockets channel
import { SubscribeMessage, WebSocketGateway } from '#nestjs/websockets'
import { Socket } from 'socket.io'
...
#WebSocketGateway()
export class MyGateway {
constructor(private readonly myService: MyService) {}
#SubscribeMessage('MY_MESSAGE')
public async sendMessage(socket: Socket, data: IData): Promise<IData> {
socket.emit(...)
}
}
and the service being in charge of the TCP channel
import { Client, ClientProxy, Transport } from '#nestjs/microservices'
...
#Injectable()
export class MyService {
#Client({
options: { host: 'MY_HOST', port: MY_PORT },
transport: Transport.TCP,
})
private client: ClientProxy
public async myFunction(): Promise<IData> {
return this.client
.send<IData>({ cmd: 'MY_MESSAGE' })
.toPromise()
.catch(error => {
throw new HttpException(error, error.status)
})
}
}

Resources