Property 'get' does not exist on type 'Cache'. NestJs project
Asked Answered
L

3

11

I'm trying to set up Redis caching for my nestjs-graphql project by following this official guide and this tutorial. I'm following the exact steps that are mentioned but I'm getting this error that Property 'get' does not exist on type 'Cache'.

Here's the exact code

import {User} from './user.entity'
import {Resolver, Query, ResolveField, Args, Parent, Mutation} from '@nestjs/graphql'
import { UsersService } from './users.service';
import { PostsService } from '../posts/posts.service';
import { CurrentUser } from 'src/auth/auth.resolver';
import { CACHE_MANAGER, Inject, UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from 'src/auth/graphql-auth.guard';
import { Cache } from 'cache-manager'; <---------this is you need to import
@Resolver(of => User)
export class UsersResolver {
  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    private usersService: UsersService,
    private postsService: PostsService,
  ) {}

  @Query()
  async getUsers() {
    const value = await this.cacheManager.get('key'); //Now .get property is working.
    if(value){                                       
      console.log({                                  
        data: value,                                 
        loadsFrom: 'redis cache'
      })
    }
    return await this.usersService.findAll();
  }
}
Lackaday answered 22/12, 2021 at 7:4 Comment(1)
Try adding the import for Cache as suggested by @ArekRGW. import { Cache } from 'cache-manager';Pelmas
P
25

Import the Cache used in

@Inject(CACHE_MANAGER) private cacheManager: Cache

from cache-manager

import { Cache } from 'cache-manager';

Providential answered 30/12, 2021 at 19:51 Comment(0)
F
1

There isn't much code but one thing that comes to my mind is that Nest couldn't resolve the dependency or it resolved it wrongly. I don't see any import of type Cache look at the docs you have provided (quote below) maybe it will help.

The Cache class is imported from the cache-manager, while CACHE_MANAGER token from the @nestjs/common package.

Firebug answered 22/12, 2021 at 9:35 Comment(0)
D
1

Thanks @Snehasish Dawn, I would upvote your answer if I could...
Cache is a default interface of typescript so it is not imported from cache-manager by default by the IDE. (link to typescript documentation)

Descant answered 8/11, 2022 at 17:59 Comment(2)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewRodriguez
It provides an answer to the error Property 'get' does not exist on type 'Cache' as @Snehasish Dawn gave the solution without explaining why... I am sorry if that was not the right place to put a comment...Descant

© 2022 - 2024 — McMap. All rights reserved.