Skip to content

Commit 1a28043

Browse files
authored
Merge pull request #141 from sourcefuse/docs
fix(api): all service docs
2 parents 85d694c + 60d310c commit 1a28043

File tree

906 files changed

+21475
-6764
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

906 files changed

+21475
-6764
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false.
1+
TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false.
Lines changed: 68 additions & 153 deletions
Original file line numberDiff line numberDiff line change
@@ -1,187 +1,102 @@
11
@sourceloop/cache / [Exports](modules.md)
22

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
44

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.
66

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+
[![LoopBack](<https://github.com/loopbackio/loopback-next/raw/master/docs/site/imgs/branding/Powered-by-LoopBack-Badge-(blue)[email protected]>)](http://loopback.io/)
428

439
## Installation
4410

11+
Install CachingComponent using `npm`;
12+
4513
```sh
46-
npm i @sourceloop/cache
14+
$ [npm install | yarn add] @sourceloop/cache
4715
```
4816

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
5418

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.
5621

5722
```ts
58-
import {
59-
CachePluginComponent,
60-
CachePluginComponentOptions,
61-
DEFAULT_CACHE_PLUGIN_OPTIONS,
62-
CachePluginComponentBindings,
63-
} from '@sourceloop/cache';
23+
import {CachingComponent} from '@sourceloop/cache';
6424
// ...
6525
export class MyApplication extends BootMixin(
6626
ServiceMixin(RepositoryMixin(RestApplication)),
6727
) {
6828
constructor(options: ApplicationConfig = {}) {
29+
this.bind(CacheComponentBindings.CacheConfig).to({
30+
ttl: 1000,
31+
strategy: RedisStoreStrategy,
32+
datasourceName: 'redisCacheStore',
33+
});
34+
this.component(CachingComponent);
6935
// ...
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);
7736
}
37+
// ...
7838
}
7939
```
8040

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
12542

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 -
12744

12845
```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);
15152
}
15253
}
15354
```
15455

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
16257

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 -
16459

16560
```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+
/// ...
181102
```
182-
183-
It uses the `prefix` to find matching entries to delete.
184-
185-
## License
186-
187-
Sourceloop is [MIT licensed](./LICENSE).

docs/arc-api-docs/packages/cache/classes/CacheManager.md

Lines changed: 0 additions & 63 deletions
This file was deleted.

docs/arc-api-docs/packages/cache/classes/CachePluginComponent.md

Lines changed: 0 additions & 55 deletions
This file was deleted.

0 commit comments

Comments
 (0)