# Cache

6.30.0+

Caching is a great and simple technique that helps improve your app's performance. It acts as a temporary data store providing high performance data access.

Ts.ED provides a unified system caching by using the popular cache-manager (opens new window) Node.js module. Cache-manager provides various storage to cache content like Redis, MongoDB, etc... and multi caching!

By using the UseCache on endpoint methods or on service methods, you'll be able to cache the response returned by the Ts.ED server or the result returned by a Service.

# Configuration

Cache-manager module is already installed with the @tsed/common package (since v6.30.0). You just have to configure cache options and use the decorator to enable cache.

import {Configuration} from "@tsed/common";

@Configuration({
  cache: {
    ttl: 300, // default TTL
    store: "memory"
    // options options depending on the choosen storage type
  }
})
export class Server {}
1
2
3
4
5
6
7
8
9
10

# Store Engines

# Example with mongoose

import {Configuration} from "@tsed/common";
import mongoose from "mongoose";

const mongooseStore = require("cache-manager-mongoose");

@Configuration({
  cache: {
    ttl: 300, // default TTL
    store: mongooseStore,
    mongoose,
    modelOptions: {
      collection: "caches",
      versionKey: false
    }
  }
})
export class Server {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# Interacting with the cache store

To interact with the cache manager instance, inject it to your class using the PlatformCache token, as follows:

@Injectable()
export class MyService {
  @Inject()
  cache: PlatformCache;
}
1
2
3
4
5

The get method on the PlatformCache instance is used to retrieve items from the cache.

const value = await this.cache.get('key');
1

To add an item to the cache, use the set method:

await this.cache.set('key', 'value');
1

The default expiration time of the cache depends on the configured TTL on Server configuration level.

You can manually specify a TTL (expiration time) for this specific key, as follows:

await this.cache.set('key', 'value', { ttl: 1000 });
1

To disable the expiration of the cache, set the ttl configuration property to null:

await this.cache.set('key', 'value', { ttl: null });
1

To remove an item from the cache, use the del method:

await this.cache.del('key');
1

To clear the entire cache, use the reset method:

await this.cache.reset();
1

# Cache response

To enable cache on endpoint, use UseCache decorator on a method as follows:

import {Controller, UseCache, Get, PathParams} from "@tsed/common";

@Controller("/my-path")
export class MyController {
  @Get("/:id")
  @UseCache()
  get(@PathParams("id") id: string) {
    return "something with  " + id;
  }
}
1
2
3
4
5
6
7
8
9
10

Note

UseCache will generate automatically a key based on the Verb and Uri of your route. If QueryParams and/or PathParams are used on the method, the key will be generated with them. According to our previous example, the generated key will be:

GET:my-path:1  // if the id is 1
GET:my-path:2  // etc...
1
2

WARNING

Only GET endpoints are cached. Also, HTTP server routes that use the native response object ( Res ) cannot use the PlatformCacheInterceptor .

# Cache a value

Because UseCache uses PlatformCacheInterceptor and not a middleware, you can also apply the decorator on any Service/Provider.

import {Injectable} from "@tsed/di";
import {UseCache} from "@tsed/common";

@Injectable()
export class MyService {
  @UseCache()
  get(id: string) {
    return "something with " + id;
  }
}
1
2
3
4
5
6
7
8
9
10

WARNING

node-cache-manager serialize all data as JSON object. It means, if you want to cache a complex data like an instance of class, you have to give extra parameters to the UseCache decorator. Ts.ED will use deserialize function based on the given type (and collectionType) to return the expected instance.

import {Injectable} from "@tsed/di";
import {UseCache} from "@tsed/common";

@Injectable()
export class MyService {
  @UseCache({type: MyClass})
  get(id: string): MyClass {
    return new MyClass({id});
  }
  
  @UseCache({type: MyClass, collectionType: Array})
  getAll(): MyClass[] {
    return [new MyClass({id: 1})];
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# Configure key resolver

By default, Ts.ED uses the request VERB & URL (in an HTTP app) or cache key (for other Service and Provider) to associate cache records with your endpoints. Nevertheless, sometimes you might want to set up the generated key based on different factors, for example, using HTTP headers (e.g. Authorization to properly identify profile endpoints).

There are two ways to do that. The first one is to configure it globally on the Server:

import {Configuration} from "@tsed/di";
import {PlatformContext} from "@tsed/common";

@Configuration({
  cache: {
    keyResolver(args: any[], $ctx?: PlatformContext): string {
      // NOTE $ctx is only available for endpoints
      return "key"
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11

The second way is to use the key option with UseCache decorator:

import {Controller, UseCache, Get, PathParams, PlatformContext} from "@tsed/common";

@Controller("/my-path")
export class MyController {
  @Get("/:id")
  @UseCache({ key: 'key' })
  get(@PathParams("id") id: string) {
    return "something with  " + id;
  }

  @Get("/:id")
  @UseCache({ key: (args: any[], $ctx?: PlatformContext) => 'key' })
  get(@PathParams("id") id: string) {
    return "something with  " + id;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# Configure TTL

TTL can be defined per endpoint with UseCache :

import {Controller, UseCache, Get, PathParams, PlatformContext} from "@tsed/common";

@Controller("/my-path")
export class MyController {
  @Get("/:id")
  @UseCache({ttl: 500})
  get(@PathParams("id") id: string) {
    return "something with  " + id;
  }
}
1
2
3
4
5
6
7
8
9
10

# Multi caching

Cache-manager provides a way to use multiple caches. To use it, remove store option and use caches instead:

import {Configuration} from "@tsed/common";

@Configuration({
  cache: {
    ttl: 300, // default TTL
    caches: [memoryCache, someOtherCache]
    // options options depending on the choosen storage type
  }
})
export class Server {}
1
2
3
4
5
6
7
8
9
10

# Disable cache for test

It can sometimes be useful during unit tests to disable the cache. You can do this by setting the cache option to false:

describe("MyCtrl", () => {
  let request: SuperTest.SuperTest<SuperTest.Test>;
  beforeAll(
    TestMongooseContext.bootstrap(Server, {
      cache: false,
      mount: {
        "/rest": [MyCtrl]
      }
    })
  );
});
1
2
3
4
5
6
7
8
9
10
11

Last Updated: 9/17/2021, 8:57:54 AM

Other topics