@things-factory/cache-service 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/assets/images/hatiolab-logo.png +0 -0
- package/config/config.development.js +17 -0
- package/config/config.production.js +17 -0
- package/dist-server/controllers/cache-service-database.d.ts +33 -0
- package/dist-server/controllers/cache-service-database.js +76 -0
- package/dist-server/controllers/cache-service-database.js.map +1 -0
- package/dist-server/controllers/cache-service-redis.d.ts +34 -0
- package/dist-server/controllers/cache-service-redis.js +65 -0
- package/dist-server/controllers/cache-service-redis.js.map +1 -0
- package/dist-server/controllers/cache-service.d.ts +2 -0
- package/dist-server/controllers/cache-service.js +11 -0
- package/dist-server/controllers/cache-service.js.map +1 -0
- package/dist-server/controllers/types.d.ts +24 -0
- package/dist-server/controllers/types.js +3 -0
- package/dist-server/controllers/types.js.map +1 -0
- package/dist-server/index.d.ts +2 -0
- package/dist-server/index.js +6 -0
- package/dist-server/index.js.map +1 -0
- package/dist-server/service/cache-store/cache-store.d.ts +8 -0
- package/dist-server/service/cache-store/cache-store.js +39 -0
- package/dist-server/service/cache-store/cache-store.js.map +1 -0
- package/dist-server/service/cache-store/index.d.ts +2 -0
- package/dist-server/service/cache-store/index.js +6 -0
- package/dist-server/service/cache-store/index.js.map +1 -0
- package/dist-server/service/index.d.ts +1 -0
- package/dist-server/service/index.js +6 -0
- package/dist-server/service/index.js.map +1 -0
- package/dist-server/tsconfig.tsbuildinfo +1 -0
- package/helps/cache-service/cache-service.ja.md +97 -0
- package/helps/cache-service/cache-service.ko.md +35 -0
- package/helps/cache-service/cache-service.md +97 -0
- package/helps/cache-service/cache-service.ms.md +99 -0
- package/helps/cache-service/cache-service.zh.md +97 -0
- package/helps/config/cache.ja.md +97 -0
- package/helps/config/cache.ko.md +97 -0
- package/helps/config/cache.md +97 -0
- package/helps/config/cache.ms.md +99 -0
- package/helps/config/cache.zh.md +97 -0
- package/package.json +34 -0
- package/server/controllers/cache-service-database.ts +78 -0
- package/server/controllers/cache-service-redis.ts +73 -0
- package/server/controllers/cache-service.ts +12 -0
- package/server/controllers/types.ts +25 -0
- package/server/index.ts +3 -0
- package/server/service/cache-store/cache-store.ts +25 -0
- package/server/service/cache-store/index.ts +3 -0
- package/server/service/index.ts +3 -0
- package/server/tsconfig.json +10 -0
- package/things-factory.config.js +1 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Cache Configuration
|
|
2
|
+
|
|
3
|
+
This configuration allows you to set up the caching mechanism for your application. You can choose between using a database or Redis for caching based on your needs.
|
|
4
|
+
|
|
5
|
+
## Default
|
|
6
|
+
|
|
7
|
+
```javascript
|
|
8
|
+
module.exports = {
|
|
9
|
+
/*
|
|
10
|
+
* cache configuration
|
|
11
|
+
* ie.
|
|
12
|
+
* cache: {
|
|
13
|
+
* middleware: 'redis', // database, redis
|
|
14
|
+
* host: 'redis',
|
|
15
|
+
* port: 6379,
|
|
16
|
+
* options: {
|
|
17
|
+
* ...
|
|
18
|
+
* }
|
|
19
|
+
* }
|
|
20
|
+
*/
|
|
21
|
+
cache: {
|
|
22
|
+
middleware: 'database' /* 'database' | 'redis' */
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Explanation
|
|
28
|
+
|
|
29
|
+
### Middleware Options
|
|
30
|
+
|
|
31
|
+
You can specify which middleware to use for caching by setting the `middleware` option. The available options are:
|
|
32
|
+
|
|
33
|
+
- **`database`**: Use the database for caching. This is suitable if you prefer to store cache data in your existing database.
|
|
34
|
+
- **`redis`**: Use Redis for caching. Redis is an in-memory data store that is optimized for fast data access and is commonly used for caching.
|
|
35
|
+
|
|
36
|
+
### Configuration Structure
|
|
37
|
+
|
|
38
|
+
The configuration object can include the following properties:
|
|
39
|
+
|
|
40
|
+
- **`middleware`**: Specifies the caching middleware to use. It can be either `'database'` or `'redis'`.
|
|
41
|
+
- **`host`** (Optional): If you choose Redis as your middleware, you can specify the Redis server's host. The default host is typically `localhost`.
|
|
42
|
+
- **`port`** (Optional): If you choose Redis as your middleware, you can specify the Redis server's port. The default port for Redis is `6379`.
|
|
43
|
+
- **`options`** (Optional): Additional options for the Redis client, such as authentication settings, TLS options, and other Redis client configurations.
|
|
44
|
+
|
|
45
|
+
### Example Configurations
|
|
46
|
+
|
|
47
|
+
#### Using Database for Caching
|
|
48
|
+
|
|
49
|
+
To use the database for caching, set the `middleware` to `'database'`:
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
module.exports = {
|
|
53
|
+
cache: {
|
|
54
|
+
middleware: 'database'
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
#### Using Redis for Caching
|
|
60
|
+
|
|
61
|
+
To use Redis for caching, set the `middleware` to `'redis'` and specify the Redis server details:
|
|
62
|
+
|
|
63
|
+
```javascript
|
|
64
|
+
module.exports = {
|
|
65
|
+
cache: {
|
|
66
|
+
middleware: 'redis',
|
|
67
|
+
host: 'redis-server-host', // Default is 'localhost'
|
|
68
|
+
port: 6379, // Default port for Redis
|
|
69
|
+
options: {
|
|
70
|
+
// Additional Redis options can be specified here
|
|
71
|
+
password: 'your-redis-password',
|
|
72
|
+
tls: {
|
|
73
|
+
// TLS settings if using a secure connection
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Usage
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
import { cacheService } from '@things-factory/cache-service'
|
|
84
|
+
;(async () => {
|
|
85
|
+
const id = 'user123'
|
|
86
|
+
const objParam = { param1: 'value1', param2: 'value2' }
|
|
87
|
+
const value = { data: 'cached data' }
|
|
88
|
+
const ttl = 3600 // 1 hour
|
|
89
|
+
|
|
90
|
+
await CacheService.setInCache(id, objParam, value, ttl)
|
|
91
|
+
|
|
92
|
+
const cachedValue = await CacheService.getFromCache(id, objParam)
|
|
93
|
+
console.log(cachedValue) // { data: 'cached data' }
|
|
94
|
+
})()
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
By configuring the caching middleware, you can optimize your application's performance based on your infrastructure and requirements.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Konfigurasi Cache
|
|
2
|
+
|
|
3
|
+
Konfigurasi ini membolehkan anda menyediakan mekanisme cache untuk aplikasi anda. Anda boleh memilih antara menggunakan pangkalan data atau Redis untuk cache berdasarkan keperluan anda.
|
|
4
|
+
|
|
5
|
+
## Lalai
|
|
6
|
+
|
|
7
|
+
```javascript
|
|
8
|
+
module.exports = {
|
|
9
|
+
/*
|
|
10
|
+
* konfigurasi cache
|
|
11
|
+
* contohnya:
|
|
12
|
+
* cache: {
|
|
13
|
+
* middleware: 'redis', // database, redis
|
|
14
|
+
* host: 'redis',
|
|
15
|
+
* port: 6379,
|
|
16
|
+
* options: {
|
|
17
|
+
* ...
|
|
18
|
+
* }
|
|
19
|
+
* }
|
|
20
|
+
*/
|
|
21
|
+
cache: {
|
|
22
|
+
middleware: 'database' /* 'database' | 'redis' */
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Penjelasan
|
|
28
|
+
|
|
29
|
+
### Pilihan Middleware
|
|
30
|
+
|
|
31
|
+
Anda boleh menentukan middleware mana yang akan digunakan untuk cache dengan menetapkan pilihan `middleware`. Pilihan yang tersedia adalah:
|
|
32
|
+
|
|
33
|
+
- **`database`**: Menggunakan pangkalan data untuk cache. Ini sesuai jika anda ingin menyimpan data cache dalam pangkalan data sedia ada.
|
|
34
|
+
- **`redis`**: Menggunakan Redis untuk cache. Redis adalah stor data dalam memori yang dioptimumkan untuk akses data yang pantas dan biasa digunakan untuk cache.
|
|
35
|
+
|
|
36
|
+
### Struktur Konfigurasi
|
|
37
|
+
|
|
38
|
+
Objek konfigurasi boleh termasuk sifat-sifat berikut:
|
|
39
|
+
|
|
40
|
+
- **`middleware`**: Menentukan middleware cache yang akan digunakan. Ia boleh menjadi sama ada `'database'` atau `'redis'`.
|
|
41
|
+
- **`host`** (Pilihan): Jika anda memilih Redis sebagai middleware, anda boleh menentukan hos pelayan Redis. Hos lalai biasanya `localhost`.
|
|
42
|
+
- **`port`** (Pilihan): Jika anda memilih Redis sebagai middleware, anda boleh menentukan port pelayan Redis. Port lalai untuk Redis adalah `6379`.
|
|
43
|
+
- **`options`** (Pilihan): Pilihan tambahan untuk klien Redis, seperti tetapan pengesahan, pilihan TLS, dan konfigurasi klien Redis yang lain.
|
|
44
|
+
|
|
45
|
+
### Contoh Konfigurasi
|
|
46
|
+
|
|
47
|
+
#### Menggunakan Pangkalan Data untuk Cache
|
|
48
|
+
|
|
49
|
+
Untuk menggunakan pangkalan data untuk cache, tetapkan `middleware`
|
|
50
|
+
|
|
51
|
+
kepada `'database'`:
|
|
52
|
+
|
|
53
|
+
```javascript
|
|
54
|
+
module.exports = {
|
|
55
|
+
cache: {
|
|
56
|
+
middleware: 'database'
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
#### Menggunakan Redis untuk Cache
|
|
62
|
+
|
|
63
|
+
Untuk menggunakan Redis untuk cache, tetapkan `middleware` kepada `'redis'` dan tentukan butiran pelayan Redis:
|
|
64
|
+
|
|
65
|
+
```javascript
|
|
66
|
+
module.exports = {
|
|
67
|
+
cache: {
|
|
68
|
+
middleware: 'redis',
|
|
69
|
+
host: 'redis-server-host', // Lalai ialah 'localhost'
|
|
70
|
+
port: 6379, // Port lalai untuk Redis
|
|
71
|
+
options: {
|
|
72
|
+
// Pilihan Redis tambahan boleh dinyatakan di sini
|
|
73
|
+
password: 'your-redis-password',
|
|
74
|
+
tls: {
|
|
75
|
+
// Tetapan TLS jika menggunakan sambungan selamat
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Penggunaan
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
import { cacheService } from '@things-factory/cache-service'
|
|
86
|
+
;(async () => {
|
|
87
|
+
const id = 'user123'
|
|
88
|
+
const objParam = { param1: 'value1', param2: 'value2' }
|
|
89
|
+
const value = { data: 'cached data' }
|
|
90
|
+
const ttl = 3600 // 1 jam
|
|
91
|
+
|
|
92
|
+
await CacheService.setInCache(id, objParam, value, ttl)
|
|
93
|
+
|
|
94
|
+
const cachedValue = await CacheService.getFromCache(id, objParam)
|
|
95
|
+
console.log(cachedValue) // { data: 'cached data' }
|
|
96
|
+
})()
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Dengan mengkonfigurasi middleware cache, anda boleh mengoptimumkan prestasi aplikasi anda berdasarkan infrastruktur dan keperluan anda.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# 缓存配置
|
|
2
|
+
|
|
3
|
+
此配置允许您为应用程序设置缓存机制。您可以根据需要选择使用数据库或Redis进行缓存。
|
|
4
|
+
|
|
5
|
+
## 默认
|
|
6
|
+
|
|
7
|
+
```javascript
|
|
8
|
+
module.exports = {
|
|
9
|
+
/*
|
|
10
|
+
* 缓存配置
|
|
11
|
+
* 例如:
|
|
12
|
+
* cache: {
|
|
13
|
+
* middleware: 'redis', // database, redis
|
|
14
|
+
* host: 'redis',
|
|
15
|
+
* port: 6379,
|
|
16
|
+
* options: {
|
|
17
|
+
* ...
|
|
18
|
+
* }
|
|
19
|
+
* }
|
|
20
|
+
*/
|
|
21
|
+
cache: {
|
|
22
|
+
middleware: 'database' /* 'database' | 'redis' */
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 说明
|
|
28
|
+
|
|
29
|
+
### 中间件选项
|
|
30
|
+
|
|
31
|
+
您可以通过设置 `middleware` 选项指定要使用的缓存中间件。可用选项有:
|
|
32
|
+
|
|
33
|
+
- **`database`**: 使用数据库进行缓存。如果您希望将缓存数据存储在现有数据库中,这是合适的选择。
|
|
34
|
+
- **`redis`**: 使用Redis进行缓存。Redis是一种内存数据存储,优化了快速数据访问,通常用于缓存。
|
|
35
|
+
|
|
36
|
+
### 配置结构
|
|
37
|
+
|
|
38
|
+
配置对象可以包含以下属性:
|
|
39
|
+
|
|
40
|
+
- **`middleware`**: 指定要使用的缓存中间件。可以是 `'database'` 或 `'redis'`。
|
|
41
|
+
- **`host`** (可选): 如果选择Redis作为中间件,可以指定Redis服务器的主机。默认主机通常是 `localhost`。
|
|
42
|
+
- **`port`** (可选): 如果选择Redis作为中间件,可以指定Redis服务器的端口。Redis的默认端口是 `6379`。
|
|
43
|
+
- **`options`** (可选): Redis客户端的其他选项,例如身份验证设置、TLS选项和其他Redis客户端配置。
|
|
44
|
+
|
|
45
|
+
### 示例配置
|
|
46
|
+
|
|
47
|
+
#### 使用数据库进行缓存
|
|
48
|
+
|
|
49
|
+
要使用数据库进行缓存,请将 `middleware` 设置为 `'database'`:
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
module.exports = {
|
|
53
|
+
cache: {
|
|
54
|
+
middleware: 'database'
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
#### 使用Redis进行缓存
|
|
60
|
+
|
|
61
|
+
要使用Redis进行缓存,请将 `middleware` 设置为 `'redis'` 并指定Redis服务器详细信息:
|
|
62
|
+
|
|
63
|
+
```javascript
|
|
64
|
+
module.exports = {
|
|
65
|
+
cache: {
|
|
66
|
+
middleware: 'redis',
|
|
67
|
+
host: 'redis-server-host', // 默认是 'localhost'
|
|
68
|
+
port: 6379, // Redis的默认端口
|
|
69
|
+
options: {
|
|
70
|
+
// 这里可以指定其他Redis选项
|
|
71
|
+
password: 'your-redis-password',
|
|
72
|
+
tls: {
|
|
73
|
+
// 如果使用安全连接,这里可以设置TLS
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## 用法
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
import { cacheService } from '@things-factory/cache-service'
|
|
84
|
+
;(async () => {
|
|
85
|
+
const id = 'user123'
|
|
86
|
+
const objParam = { param1: 'value1', param2: 'value2' }
|
|
87
|
+
const value = { data: 'cached data' }
|
|
88
|
+
const ttl = 3600 // 1小时
|
|
89
|
+
|
|
90
|
+
await CacheService.setInCache(id, objParam, value, ttl)
|
|
91
|
+
|
|
92
|
+
const cachedValue = await CacheService.getFromCache(id, objParam)
|
|
93
|
+
console.log(cachedValue) // { data: 'cached data' }
|
|
94
|
+
})()
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
通过配置缓存中间件,您可以根据基础设施和需求优化应用程序的性能。
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@things-factory/cache-service",
|
|
3
|
+
"version": "7.0.0",
|
|
4
|
+
"main": "dist-server/index.js",
|
|
5
|
+
"things-factory": true,
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "heartyoh <heartyoh@hatiolab.com>",
|
|
8
|
+
"description": "A module for cache service",
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public",
|
|
11
|
+
"@things-factory:registry": "https://registry.npmjs.org"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/hatiolab/things-factory.git",
|
|
16
|
+
"directory": "packages/cache-service"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "npm run build:server",
|
|
20
|
+
"build:server": "npx tsc --p ./server/tsconfig.json",
|
|
21
|
+
"clean:server": "npx rimraf dist-server",
|
|
22
|
+
"clean": "npm run clean:server",
|
|
23
|
+
"migration:create": "node ../../node_modules/typeorm/cli.js migration:create -d ./server/migrations"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@operato/graphql": "^7.0.0",
|
|
27
|
+
"@operato/shell": "^7.0.0",
|
|
28
|
+
"@things-factory/auth-base": "^7.0.0",
|
|
29
|
+
"@things-factory/shell": "^7.0.0",
|
|
30
|
+
"object-hash": "^3.0.0",
|
|
31
|
+
"redis": "^4.6.14"
|
|
32
|
+
},
|
|
33
|
+
"gitHead": "00f3917ca132679e3571f3f4fd16f4caf84f488e"
|
|
34
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { getRepository } from '@things-factory/shell'
|
|
2
|
+
import { CacheStore } from '../service/cache-store/cache-store'
|
|
3
|
+
import { ICacheService } from './types'
|
|
4
|
+
import objectHash from 'object-hash'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* CacheService class implements ICacheService interface
|
|
8
|
+
* It provides methods to interact with the cache.
|
|
9
|
+
*/
|
|
10
|
+
export class CacheServiceDatabase implements ICacheService {
|
|
11
|
+
/**
|
|
12
|
+
* Generates a unique cache key using the provided id and object parameters.
|
|
13
|
+
*
|
|
14
|
+
* @param id - The unique identifier for the cache entry.
|
|
15
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
16
|
+
* @returns The generated cache key.
|
|
17
|
+
*/
|
|
18
|
+
private generateCacheKey(objParam: object): string {
|
|
19
|
+
return objParam ? objectHash(objParam) : objectHash({})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Retrieves an entry from the cache.
|
|
24
|
+
*
|
|
25
|
+
* @param id - The unique identifier for the cache entry.
|
|
26
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
27
|
+
* @returns A promise that resolves to the cached entry or null if not found or expired.
|
|
28
|
+
*/
|
|
29
|
+
async getFromCache(id: string, objParam: object): Promise<any> {
|
|
30
|
+
const cacheRepository = getRepository(CacheStore)
|
|
31
|
+
|
|
32
|
+
const cacheEntry = await cacheRepository.findOne({
|
|
33
|
+
where: { cacheId: id, hashKey: this.generateCacheKey(objParam) },
|
|
34
|
+
order: { wroteAt: 'DESC' }
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
// Check if the cache entry is found and still valid
|
|
38
|
+
if (cacheEntry && cacheEntry.ttl && new Date(cacheEntry.wroteAt.getTime() + cacheEntry.ttl * 1000) > new Date()) {
|
|
39
|
+
return cacheEntry
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Stores an entry in the cache.
|
|
47
|
+
*
|
|
48
|
+
* @param id - The unique identifier for the cache entry.
|
|
49
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
50
|
+
* @param value - The value to be cached.
|
|
51
|
+
* @param ttl - Time to live in seconds. After this period, the cache entry expires.
|
|
52
|
+
* @returns A promise that resolves when the entry is successfully stored.
|
|
53
|
+
*/
|
|
54
|
+
async setInCache(id: string, objParam: object, value: any, ttl: number): Promise<void> {
|
|
55
|
+
const key = this.generateCacheKey(objParam)
|
|
56
|
+
const wroteAt = new Date()
|
|
57
|
+
|
|
58
|
+
const cacheRepository = getRepository(CacheStore)
|
|
59
|
+
let cacheEntry = await cacheRepository.findOne({ where: { cacheId: id, hashKey: key } })
|
|
60
|
+
|
|
61
|
+
if (!cacheEntry) {
|
|
62
|
+
// Create a new cache entry
|
|
63
|
+
cacheEntry = new CacheStore()
|
|
64
|
+
cacheEntry.cacheId = id
|
|
65
|
+
cacheEntry.hashKey = key
|
|
66
|
+
cacheEntry.value = value
|
|
67
|
+
cacheEntry.ttl = ttl
|
|
68
|
+
cacheEntry.wroteAt = wroteAt
|
|
69
|
+
await cacheRepository.save(cacheEntry)
|
|
70
|
+
} else {
|
|
71
|
+
// Update the existing cache entry
|
|
72
|
+
cacheEntry.value = value
|
|
73
|
+
cacheEntry.ttl = ttl
|
|
74
|
+
cacheEntry.wroteAt = wroteAt
|
|
75
|
+
await cacheRepository.save(cacheEntry)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { ICacheService } from './types'
|
|
2
|
+
import objectHash from 'object-hash'
|
|
3
|
+
import { createClient } from 'redis'
|
|
4
|
+
import { promisify } from 'util'
|
|
5
|
+
import { config } from '@things-factory/env'
|
|
6
|
+
|
|
7
|
+
const cacheConfig = config.get('cache', {
|
|
8
|
+
middleware: 'redis',
|
|
9
|
+
host: 'localhost',
|
|
10
|
+
port: 6379
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
const { host, port } = cacheConfig || {}
|
|
14
|
+
|
|
15
|
+
export class CacheServiceRedis implements ICacheService {
|
|
16
|
+
private client
|
|
17
|
+
private getAsync: (key: string) => Promise<string | null>
|
|
18
|
+
private setAsync: (key: string, value: string) => Promise<void>
|
|
19
|
+
private expireAsync: (key: string, seconds: number) => Promise<void>
|
|
20
|
+
|
|
21
|
+
constructor() {
|
|
22
|
+
this.client = createClient({
|
|
23
|
+
url: `redis://${host}:${port}`
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
this.getAsync = promisify(this.client.get).bind(this.client)
|
|
27
|
+
this.setAsync = promisify(this.client.set).bind(this.client)
|
|
28
|
+
this.expireAsync = promisify(this.client.expire).bind(this.client)
|
|
29
|
+
|
|
30
|
+
this.client.connect().catch(console.error)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Generates a unique cache key using the provided id and object parameters.
|
|
35
|
+
*
|
|
36
|
+
* @param id - The unique identifier for the cache entry.
|
|
37
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
38
|
+
* @returns The generated cache key.
|
|
39
|
+
*/
|
|
40
|
+
private generateCacheKey(id: string, objParam: object): string {
|
|
41
|
+
const hash = objectHash(objParam)
|
|
42
|
+
return `${id}_${hash}`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Retrieves an entry from the cache.
|
|
47
|
+
*
|
|
48
|
+
* @param id - The unique identifier for the cache entry.
|
|
49
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
50
|
+
* @returns A promise that resolves to the cached entry or null if not found or expired.
|
|
51
|
+
*/
|
|
52
|
+
async getFromCache(id: string, objParam: object): Promise<any> {
|
|
53
|
+
const key = this.generateCacheKey(id, objParam)
|
|
54
|
+
const cacheEntry = await this.getAsync(key)
|
|
55
|
+
return cacheEntry ? JSON.parse(cacheEntry) : null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Stores an entry in the cache.
|
|
60
|
+
*
|
|
61
|
+
* @param id - The unique identifier for the cache entry.
|
|
62
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
63
|
+
* @param value - The value to be cached.
|
|
64
|
+
* @param ttl - Time to live in seconds. After this period, the cache entry expires.
|
|
65
|
+
* @returns A promise that resolves when the entry is successfully stored.
|
|
66
|
+
*/
|
|
67
|
+
async setInCache(id: string, objParam: object, value: any, ttl: number): Promise<void> {
|
|
68
|
+
const key = this.generateCacheKey(id, objParam)
|
|
69
|
+
const cacheValue = JSON.stringify(value)
|
|
70
|
+
await this.setAsync(key, cacheValue)
|
|
71
|
+
await this.expireAsync(key, ttl)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ICacheService } from './types'
|
|
2
|
+
import { config } from '@things-factory/env'
|
|
3
|
+
|
|
4
|
+
const cacheConfig = config.get('cache', {
|
|
5
|
+
middleware: 'database'
|
|
6
|
+
})
|
|
7
|
+
|
|
8
|
+
const { CacheServiceDatabase } = require('./cache-service-database')
|
|
9
|
+
const { CacheServiceRedis } = require('./cache-service-redis')
|
|
10
|
+
|
|
11
|
+
export const cacheService: ICacheService =
|
|
12
|
+
cacheConfig.middleware == 'redis' ? new CacheServiceRedis() : new CacheServiceDatabase()
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interface representing a cache service.
|
|
3
|
+
* Provides methods to get and set values in a cache.
|
|
4
|
+
*/
|
|
5
|
+
export interface ICacheService {
|
|
6
|
+
/**
|
|
7
|
+
* Retrieves a value from the cache.
|
|
8
|
+
*
|
|
9
|
+
* @param id - The unique identifier for the cache entry.
|
|
10
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
11
|
+
* @returns A promise that resolves to the cached value, or null if the key is not found.
|
|
12
|
+
*/
|
|
13
|
+
getFromCache(id: string, objParam: object): Promise<any>
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Stores a value in the cache.
|
|
17
|
+
*
|
|
18
|
+
* @param id - The unique identifier for the cache entry.
|
|
19
|
+
* @param objParam - The object parameters that are part of the cache key.
|
|
20
|
+
* @param value - The value to be cached.
|
|
21
|
+
* @param ttl - Time to live in seconds. After this period, the cache entry expires.
|
|
22
|
+
* @returns A promise that resolves when the value is successfully stored.
|
|
23
|
+
*/
|
|
24
|
+
setInCache(id: string, objParam: object, value: any, ttl: number): Promise<void>
|
|
25
|
+
}
|
package/server/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Entity, Index, Column, PrimaryGeneratedColumn } from 'typeorm'
|
|
2
|
+
|
|
3
|
+
@Entity()
|
|
4
|
+
@Index('ix_cache_store_0', (cache: CacheStore) => [cache.cacheId, cache.hashKey], {
|
|
5
|
+
unique: true
|
|
6
|
+
})
|
|
7
|
+
export class CacheStore {
|
|
8
|
+
@PrimaryGeneratedColumn('uuid')
|
|
9
|
+
readonly id: string
|
|
10
|
+
|
|
11
|
+
@Column()
|
|
12
|
+
cacheId?: string
|
|
13
|
+
|
|
14
|
+
@Column()
|
|
15
|
+
hashKey?: string
|
|
16
|
+
|
|
17
|
+
@Column('simple-json', { nullable: true, default: null })
|
|
18
|
+
value?: any
|
|
19
|
+
|
|
20
|
+
@Column({ nullable: true, default: null })
|
|
21
|
+
ttl?: number
|
|
22
|
+
|
|
23
|
+
@Column({ nullable: true })
|
|
24
|
+
wroteAt?: Date
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default {}
|