|
1 | 1 | @sourceloop/cache / [Exports](modules.md) |
2 | 2 |
|
3 | | -<a href="https://sourcefuse.github.io/arc-docs/arc-api-docs" target="_blank"><img src="https://github.com/sourcefuse/loopback4-microservice-catalog/blob/master/docs/assets/logo-dark-bg.png?raw=true" alt="ARC By SourceFuse logo" title="ARC By SourceFuse" align="right" width="150" /></a> |
| 3 | +# caching-guard |
4 | 4 |
|
5 | | -# [@sourceloop/cache](https://github.com/sourcefuse/loopback4-microservice-catalog/tree/master/packages/cache) |
| 5 | +A Caching component that provides helpers for caching in Loopback4 based microservices. |
6 | 6 |
|
7 | | -<p align="left"> |
8 | | -<a href="https://www.npmjs.org/package/@sourceloop/cache"> |
9 | | -<img src="https://img.shields.io/npm/v/@sourceloop/cache.svg" alt="npm version" /> |
10 | | -</a> |
11 | | -<a href="https://github.com/sourcefuse/loopback4-microservice-catalog/graphs/contributors" target="_blank"> |
12 | | -<img alt="GitHub contributors" src="https://img.shields.io/github/contributors/sourcefuse/loopback4-microservice-catalog"> |
13 | | -</a> |
14 | | -<a href="https://www.npmjs.com/@sourceloop/cache" target="_blank"> |
15 | | -<img alt="sourceloop cache downloads" src="https://img.shields.io/npm/dm/@sourceloop/cache"> |
16 | | -</a> |
17 | | -<a href="./LICENSE"> |
18 | | -<img src="https://img.shields.io/github/license/sourcefuse/loopback4-microservice-catalog" alt="License" /> |
19 | | -</a> |
20 | | -<a href="https://loopback.io/" target="_blank"> |
21 | | -<img alt="Pb Loopback" src="https://img.shields.io/badge/Powered%20by-Loopback 4-brightgreen" /> |
22 | | -</a> |
23 | | -</p> |
24 | | - |
25 | | -## Overview |
26 | | - |
27 | | -The `@sourceloop/cache` package offers a flexible solution for implementing caching in LoopBack. It introduces a mixin for LoopBack's [DefaultCrudRepository](https://loopback.io/doc/en/lb4/apidocs.repository.defaultcrudrepository.html) and [SequelizeCrudRepository](https://loopback.io/doc/en/lb4/apidocs.sequelize.sequelizecrudrepository.html), allowing you to configure caching behavior. This mixin extends and overrides the `find`, `findById`, and `findOne` methods of the target repository. By leveraging [Redis](https://redis.io) as the caching datasource, it enables the caching of GET request responses. |
28 | | - |
29 | | -## Philosophy |
30 | | - |
31 | | -Caching can prove to be quite beneficial in improving application efficency and performance by storing a subset of data in high speed data storage layer. Some benefits that cache can provide: |
32 | | - |
33 | | -- It allows you to efficiently reuse previously retrieved or computed data. |
34 | | -- It reduces latency. |
35 | | -- It helps to avoids network congestion. |
36 | | -- In the event of outages, it can save the day by serving end users with the cached content. |
37 | | - |
38 | | -However, cache can't be used anywhere. You must consider the following: |
39 | | - |
40 | | -- It is only beneficial in case same data is frequently requested (i.e. cache hit rate should be high). If this is not the case then caching will prove to be an overhead for your application |
41 | | -- In case of caching editable data, you must be prepared to receive stale data from cache. However, you can configure the ttl according to whatever is acceptable for your application. |
| 7 | +[[email protected]>)](http://loopback.io/) |
42 | 8 |
|
43 | 9 | ## Installation |
44 | 10 |
|
| 11 | +Install CachingComponent using `npm`; |
| 12 | + |
45 | 13 | ```sh |
46 | | -npm i @sourceloop/cache |
| 14 | +$ [npm install | yarn add] @sourceloop/cache |
47 | 15 | ``` |
48 | 16 |
|
49 | | -Note: This package has [loopback-connector-kv-redis](https://www.npmjs.com/package/loopback-connector-kv-redis) as a peer dependency and only works with Redis for now. |
50 | | - |
51 | | -## Usage |
52 | | - |
53 | | -### Component Binding |
| 17 | +## Basic Usage |
54 | 18 |
|
55 | | -Configure and bind `CachePluginComponent` to the application constructor as shown below. |
| 19 | +Configure and load CachingComponent in the application constructor |
| 20 | +as shown below. |
56 | 21 |
|
57 | 22 | ```ts |
58 | | -import { |
59 | | - CachePluginComponent, |
60 | | - CachePluginComponentOptions, |
61 | | - DEFAULT_CACHE_PLUGIN_OPTIONS, |
62 | | - CachePluginComponentBindings, |
63 | | -} from '@sourceloop/cache'; |
| 23 | +import {CachingComponent} from '@sourceloop/cache'; |
64 | 24 | // ... |
65 | 25 | export class MyApplication extends BootMixin( |
66 | 26 | ServiceMixin(RepositoryMixin(RestApplication)), |
67 | 27 | ) { |
68 | 28 | constructor(options: ApplicationConfig = {}) { |
| 29 | + this.bind(CacheComponentBindings.CacheConfig).to({ |
| 30 | + ttl: 1000, |
| 31 | + strategy: RedisStoreStrategy, |
| 32 | + datasourceName: 'redisCacheStore', |
| 33 | + }); |
| 34 | + this.component(CachingComponent); |
69 | 35 | // ... |
70 | | - const cacheOptions: CachePluginComponentOptions = { |
71 | | - cacheProvider: CacheStrategyTypes.Redis, |
72 | | - prefix: process.env.CACHE_PREFIX ?? DEFAULT_CACHE_PLUGIN_OPTIONS.prefix, |
73 | | - ttl: 3000, |
74 | | - }; |
75 | | - this.configure(CachePluginComponentBindings.COMPONENT).to(cacheOptions); |
76 | | - this.component(CachePluginComponent); |
77 | 36 | } |
| 37 | + // ... |
78 | 38 | } |
79 | 39 | ``` |
80 | 40 |
|
81 | | -As shown above, you can configure the cache properties at a Global level. You can also provide these properties at the repository level. Options passed at the repository level will override the global options. |
82 | | - |
83 | | -### Configuration Options |
84 | | - |
85 | | -The following options can be passed: |
86 | | - |
87 | | -<table> |
88 | | -<thead> |
89 | | -<tr> |
90 | | - <th>Property</th> |
91 | | - <th>Default Value</th> |
92 | | - <th>Description</th> |
93 | | -</tr> |
94 | | -</thead> |
95 | | -<tbody> |
96 | | - |
97 | | -<tr> |
98 | | - <td>cacheProvider</td> |
99 | | - <td>Redis</td> |
100 | | - <td> |
101 | | - |
102 | | -cacheProvider specifies the cache provider to be used. `CacheStrategyTypes.Redis` indicates that Redis is the chosen cache provider. |
103 | | - |
104 | | -</td> |
105 | | -</tr> |
106 | | -<tr> |
107 | | - <td>prefix</td> |
108 | | - <td>sl</td> |
109 | | - <td>Prefix is applied in the key of every cached entry when storing it inside caching provider. Each repository should have their own unique prefix.</td> |
110 | | -</tr> |
111 | | -<tr> |
112 | | - <td>ttl</td> |
113 | | - <td>60000</td> |
114 | | - <td>TTL (time to live) is the maximum time in milliseconds for which data will remain cached in the caching provider. In other words this can be called the amount of time for which stale data is acceptable.</td> |
115 | | -</tr> |
116 | | - |
117 | | -</tbody> |
118 | | -</table> |
119 | | - |
120 | | -> NOTE : The caching is implemented as a key value pair. The key is in the form of `{{prefix}}_{{id}}_{{filter}}`. The format of the key plays a very important role in the cache hit ratio. For example: Consider a situation in which you are sending user id in filter with every request. This will generate a new key for every user. So even if same data is returned to all users, caching will not be beneficial until and unless the same user makes the same request multiple times. |
121 | | -
|
122 | | -### Apply Mixin to Repository |
123 | | - |
124 | | -To use the caching functionality, you need to apply `CacheRespositoryMixin` provided in `CacheManager` class exported by this package to your repository. |
| 41 | +### In a repository |
125 | 42 |
|
126 | | -Alongside You must inject the getter of the cache datasource with variable name `getCacheDataSource` in your repository's constructor, like below: |
| 43 | +To add caching to a repository, just add it as a mixin to the base class - |
127 | 44 |
|
128 | 45 | ```ts |
129 | | -export class ProductRepository extends CacheManager.CacheRepositoryMixin< |
130 | | - Product, |
131 | | - typeof Product.prototype.id, |
132 | | - ProductRelations, |
133 | | - Constructor< |
134 | | - DefaultCrudRepository< |
135 | | - Product, |
136 | | - typeof Product.prototype.id, |
137 | | - ProductRelations |
138 | | - > |
139 | | - > |
140 | | ->(DefaultCrudRepository, { |
141 | | - prefix: 'product', |
142 | | - ttl: 50000, |
143 | | -}) { |
144 | | - redisDataSource: RedisDataSource; |
145 | | - constructor( |
146 | | - @inject('datasources.expt') dataSource: ExptDataSource, |
147 | | - @inject.getter('datasources.CacheDB') |
148 | | - public getCacheDataSource: Getter<RedisDataSource>, |
149 | | - ) { |
150 | | - super(Product, dataSource); |
| 46 | +export class TestWithMixinRepository extends CacheMixin( |
| 47 | + DefaultCrudRepository<Test, number, {}>, |
| 48 | +) { |
| 49 | + cacheIdentifier = 'testRepo'; |
| 50 | + constructor(@inject('datasources.memorydb') dataSource: juggler.DataSource) { |
| 51 | + super(Test, dataSource); |
151 | 52 | } |
152 | 53 | } |
153 | 54 | ``` |
154 | 55 |
|
155 | | -### Using It With Sequelize |
156 | | - |
157 | | -`CacheRepositoryMixin` starting `v0.5.0` supports the [SequelizeCrudRepository](https://loopback.io/doc/en/lb4/apidocs.sequelize.sequelizecrudrepository.html). |
158 | | - |
159 | | -Checkout [@loopback/sequelize](https://www.npmjs.com/package/@loopback/sequelize) for more information on how to use sequelize in your project. |
160 | | - |
161 | | -### Force Update |
| 56 | +### In a controller or service |
162 | 57 |
|
163 | | -To forcefully update entries in cache, you can set `forceUpdate` to `true` in `options` parameter while invoking `find`, `findById` or `findOne`. Forcefully update will always return data from the original source and update the cache with the new data. |
| 58 | +To add caching to a service or controller, just implement the `ICachedService` interface, adding a binding for the `ICacheService` and the applying the relevant decorators to the methods you want cached - |
164 | 59 |
|
165 | 60 | ```ts |
166 | | -this.productRepository.findById(3, {}, {forceUpdate: true}); |
167 | | -``` |
168 | | - |
169 | | -On updating forcefully the `ttl` option gets reset. |
170 | | - |
171 | | -### Skip Cache |
172 | | - |
173 | | -There are situations where disabling the cache becomes necessary, such as in a test environment or when bypassing it for any specific reason. In such cases, you can set the environment variable `SKIP_CACHE` to `true` to skip the cache functionality altogether. |
174 | | - |
175 | | -### Clear Cache |
176 | | - |
177 | | -To delete all cached entries for a repository, you can use the `clearCache` function on the repository, like below: |
178 | | - |
179 | | -```ts |
180 | | -this.productRepository.clearCache(); |
| 61 | +export class TestController implements ICachedService { |
| 62 | + constructor( |
| 63 | + @repository(TestWithoutCachingRepository) |
| 64 | + public testModelRepository: TestWithoutCachingRepository, |
| 65 | + @inject(CacheComponentBindings.CacheService) |
| 66 | + public cache: ICacheService, |
| 67 | + ) {} |
| 68 | + cacheIdentifier = 'testRepo'; |
| 69 | + |
| 70 | + @cacheInvalidator() |
| 71 | + @post('/tests') |
| 72 | + @response(200, { |
| 73 | + description: 'Test model instance', |
| 74 | + content: {'application/json': {schema: getModelSchemaRef(Test)}}, |
| 75 | + }) |
| 76 | + async create( |
| 77 | + @requestBody({ |
| 78 | + content: { |
| 79 | + 'application/json': { |
| 80 | + schema: getModelSchemaRef(Test, { |
| 81 | + title: 'NewTest', |
| 82 | + exclude: ['id'], |
| 83 | + }), |
| 84 | + }, |
| 85 | + }, |
| 86 | + }) |
| 87 | + testModel: Omit<Test, 'id'>, |
| 88 | + ): Promise<Test> { |
| 89 | + return this.testModelRepository.create(testModel); |
| 90 | + } |
| 91 | + // ... |
| 92 | + @cachedItem() |
| 93 | + @get('/tests/count') |
| 94 | + @response(200, { |
| 95 | + description: 'Test model count', |
| 96 | + content: {'application/json': {schema: CountSchema}}, |
| 97 | + }) |
| 98 | + async count(@param.where(Test) where?: Where<Test>): Promise<Count> { |
| 99 | + return this.testModelRepository.count(where); |
| 100 | + } |
| 101 | + /// ... |
181 | 102 | ``` |
182 | | - |
183 | | -It uses the `prefix` to find matching entries to delete. |
184 | | - |
185 | | -## License |
186 | | - |
187 | | -Sourceloop is [MIT licensed](./LICENSE). |
0 commit comments