Caching queries

You can cache results selected by these QueryBuilder methods: getMany, getOne, getRawMany, getRawOne and getCount.

You can also cache results selected by these Repository methods: find, findAndCount, findByIds, and count.

To enable caching you need to explicitly enable it in your connection options:

  1. {
  2. type: "mysql",
  3. host: "localhost",
  4. username: "test",
  5. ...
  6. cache: true
  7. }

When you enable cache for the first time,you must synchronize your database schema (using CLI, migrations or the synchronize connection option).

Then in QueryBuilder you can enable query cache for any query:

  1. const users = await connection
  2. .createQueryBuilder(User, "user")
  3. .where("user.isAdmin = :isAdmin", { isAdmin: true })
  4. .cache(true)
  5. .getMany();

Equivalent Repository query:

  1. const users = await connection
  2. .getRepository(User)
  3. .find({
  4. where: { isAdmin: true },
  5. cache: true
  6. });

This will execute a query to fetch all admin users and cache the results.Next time you execute the same code, it will get all admin users from the cache.Default cache lifetime is equal to 1000 ms, e.g. 1 second.This means the cache will be invalid 1 second after the query builder code is called.In practice, this means that if users open the user page 150 times within 3 seconds, only three queries will be executed during this period.Any users inserted during the 1 second cache window won’t be returned to the user.

You can change cache time manually via QueryBuilder:

  1. const users = await connection
  2. .createQueryBuilder(User, "user")
  3. .where("user.isAdmin = :isAdmin", { isAdmin: true })
  4. .cache(60000) // 1 minute
  5. .getMany();

Or via Repository:

  1. const users = await connection
  2. .getRepository(User)
  3. .find({
  4. where: { isAdmin: true },
  5. cache: 60000
  6. });

Or globally in connection options:

  1. {
  2. type: "mysql",
  3. host: "localhost",
  4. username: "test",
  5. ...
  6. cache: {
  7. duration: 30000 // 30 seconds
  8. }
  9. }

Also, you can set a “cache id” via QueryBuilder:

  1. const users = await connection
  2. .createQueryBuilder(User, "user")
  3. .where("user.isAdmin = :isAdmin", { isAdmin: true })
  4. .cache("users_admins", 25000)
  5. .getMany();

Or with Repository:

  1. const users = await connection
  2. .getRepository(User)
  3. .find({
  4. where: { isAdmin: true },
  5. cache: {
  6. id: "users_admins",
  7. milliseconds: 25000
  8. }
  9. });

This gives you granular control of your cache,for example, clearing cached results when you insert a new user:

  1. await connection.queryResultCache.remove(["users_admins"]);

By default, TypeORM uses a separate table called query-result-cache and stores all queries and results there.Table name is configurable, so you could change its by give the value in the tableName property.Example:

  1. {
  2. type: "mysql",
  3. host: "localhost",
  4. username: "test",
  5. ...
  6. cache: {
  7. type: "database",
  8. tableName: "configurable-table-query-result-cache"
  9. }
  10. }

If storing cache in a single database table is not effective for you,you can change the cache type to “redis” or “ioredis” and TypeORM will store all cached records in redis instead.Example:

  1. {
  2. type: "mysql",
  3. host: "localhost",
  4. username: "test",
  5. ...
  6. cache: {
  7. type: "redis",
  8. options: {
  9. host: "localhost",
  10. port: 6379
  11. }
  12. }
  13. }

“options” can be node_redis specific options or ioredis specific options depending on what type you’re using.

In case you want to connect to a redis-cluster using IORedis’s cluster functionality, you can do that as well by doing the following:

  1. {
  2. type: "mysql",
  3. host: "localhost",
  4. username: "test",
  5. cache: {
  6. type: "ioredis/cluster",
  7. options: {
  8. startupNodes: [
  9. {
  10. host: 'localhost',
  11. port: 7000,
  12. },
  13. {
  14. host: 'localhost',
  15. port: 7001,
  16. },
  17. {
  18. host: 'localhost',
  19. port: 7002,
  20. }
  21. ],
  22. options: {
  23. scaleReads: 'all',
  24. clusterRetryStrategy: function (times) { return null },
  25. redisOptions: {
  26. maxRetriesPerRequest: 1
  27. }
  28. }
  29. }
  30. }
  31. }

Note that, you can still use options as first argument of IORedis’s cluster constructor.

  1. {
  2. ...
  3. cache: {
  4. type: "ioredis/cluster",
  5. options: [
  6. {
  7. host: 'localhost',
  8. port: 7000,
  9. },
  10. {
  11. host: 'localhost',
  12. port: 7001,
  13. },
  14. {
  15. host: 'localhost',
  16. port: 7002,
  17. }
  18. ]
  19. },
  20. ...
  21. }

You can use typeorm cache:clear to clear everything stored in the cache.