Get a Quote Right Now

Edit Template

Caching queries in Typeorm

You can cache results selected by these QueryBuilder methods: getManygetOnegetRawManygetRawOne and getCount.

You can also cache results selected by find* and count* methods of the Repository and EntityManager.

To enable caching you need to explicitly enable it in data source options:

{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: true
}

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

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

const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache(true)
    .getMany()

Equivalent Repository query:

const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: true,
})

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:

const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache(60000) // 1 minute
    .getMany()

Or via Repository:

const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: 60000,
})

Or globally in data source options:

{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        duration: 30000 // 30 seconds
    }
}

Share

Leave a Reply

Your email address will not be published. Required fields are marked *