koatty_cacheable 1.3.2 → 1.3.7

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/dist/index.js CHANGED
@@ -1,244 +1,199 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CacheEvict = exports.CacheAble = exports.GetCacheStore = void 0;
4
- const tslib_1 = require("tslib");
5
- /*
6
- * @Author: richen
7
- * @Date: 2020-07-06 19:53:43
8
- * @LastEditTime: 2021-07-07 11:11:05
9
- * @Description:
10
- * @Copyright (c) - <richenlin(at)gmail.com>
11
- */
12
- const helper = (0, tslib_1.__importStar)(require("koatty_lib"));
13
- const koatty_logger_1 = require("koatty_logger");
14
- const koatty_store_1 = require("koatty_store");
15
- const koatty_container_1 = require("koatty_container");
16
- // cacheStore
17
- const cacheStore = {
18
- store: null
19
- };
20
- /**
21
- * get instances of cacheStore
22
- *
23
- * @export
24
- * @returns {*}
25
- */
26
- async function GetCacheStore(app) {
27
- var _a;
28
- if (cacheStore.store && cacheStore.store.getConnection) {
29
- return cacheStore.store;
30
- }
31
- const opt = (_a = app.config("CacheStore", "db")) !== null && _a !== void 0 ? _a : {};
32
- if (helper.isEmpty(opt)) {
33
- koatty_logger_1.DefaultLogger.Warn(`Missing CacheStore server configuration. Please write a configuration item with the key name 'CacheStore' in the db.ts file.`);
34
- }
35
- cacheStore.store = koatty_store_1.Store.getInstance(opt);
36
- if (!helper.isFunction(cacheStore.store.getConnection)) {
37
- throw Error(`CacheStore connection failed. `);
38
- }
39
- return cacheStore.store;
40
- }
41
- exports.GetCacheStore = GetCacheStore;
42
- /**
43
- * initiation CacheStore connection and client.
44
- *
45
- * @param {Application} app
46
- * @returns {*} {Promise<CacheStore>}
47
- */
48
- async function InitCacheStore(app) {
49
- return GetCacheStore(app);
50
- }
51
- /**
52
- * Decorate this method to support caching. Redis server config from db.ts.
53
- * The cache method returns a value to ensure that the next time the method is executed with the same parameters,
54
- * the results can be obtained directly from the cache without the need to execute the method again.
55
- *
56
- * @export
57
- * @param {string} cacheName cache name
58
- * @param {(number | number[])} [paramKey] The index of the arguments.
59
- * @param {number} [timeout=3600] cache timeout
60
- * @returns {MethodDecorator}
61
- */
62
- function CacheAble(cacheName, paramKey, timeout = 3600) {
63
- return (target, methodName, descriptor) => {
64
- const componentType = koatty_container_1.IOCContainer.getType(target);
65
- if (componentType !== "SERVICE" && componentType !== "COMPONENT") {
66
- throw Error("This decorator only used in the service、component class.");
67
- }
68
- let identifier = koatty_container_1.IOCContainer.getIdentifier(target);
69
- identifier = identifier || (target.constructor ? (target.constructor.name || "") : "");
70
- const { value, configurable, enumerable } = descriptor;
71
- descriptor = {
72
- configurable,
73
- enumerable,
74
- writable: true,
75
- async value(...props) {
76
- let cacheFlag = true;
77
- const store = await GetCacheStore(this.app).catch(() => {
78
- cacheFlag = false;
79
- koatty_logger_1.DefaultLogger.Error("Get cache store instance failed.");
80
- return null;
1
+ /*!
2
+ * @Author: richen
3
+ * @Date: 2022-05-27 11:35:38
4
+ * @License: BSD (3-Clause)
5
+ * @Copyright (c) - <richenlin(at)gmail.com>
6
+ * @HomePage: https://koatty.org/
7
+ */
8
+ 'use strict';
9
+
10
+ Object.defineProperty(exports, '__esModule', { value: true });
11
+
12
+ var helper = require('koatty_lib');
13
+ var koatty_logger = require('koatty_logger');
14
+ var koatty_store = require('koatty_store');
15
+ var koatty_container = require('koatty_container');
16
+
17
+ function _interopNamespace(e) {
18
+ if (e && e.__esModule) return e;
19
+ var n = Object.create(null);
20
+ if (e) {
21
+ Object.keys(e).forEach(function (k) {
22
+ if (k !== 'default') {
23
+ var d = Object.getOwnPropertyDescriptor(e, k);
24
+ Object.defineProperty(n, k, d.get ? d : {
25
+ enumerable: true,
26
+ get: function () { return e[k]; }
81
27
  });
82
- if (cacheFlag) {
83
- // tslint:disable-next-line: one-variable-per-declaration
84
- let key = "", res;
85
- if (helper.isArray(paramKey)) {
86
- paramKey.map((it) => {
87
- if (!helper.isTrueEmpty(props[it])) {
88
- if (typeof props[it] === "object") {
89
- key = `${key}${helper.murmurHash(JSON.stringify(props[it]))}`;
90
- }
91
- else {
92
- key = `${key}${props[it] || ''}`;
93
- }
94
- }
95
- });
96
- }
97
- else if (helper.isNumber(paramKey)) {
98
- if (typeof props[paramKey] === "object") {
99
- key = helper.murmurHash(JSON.stringify(props[paramKey]));
100
- }
101
- else {
102
- key = props[paramKey] || "";
103
- }
104
- }
105
- else {
106
- key = `${identifier}:${methodName}`;
107
- }
108
- if (!helper.isTrueEmpty(key)) {
109
- res = await store.get(`${cacheName}:${key}`).catch(() => null);
110
- }
111
- else {
112
- res = await store.get(cacheName).catch(() => null);
113
- }
114
- try {
115
- res = JSON.parse(res || "");
116
- }
117
- catch (e) {
118
- res = null;
119
- }
120
- if (helper.isEmpty(res)) {
121
- // tslint:disable-next-line: no-invalid-this
122
- res = await value.apply(this, props);
123
- // prevent cache penetration
124
- if (helper.isEmpty(res)) {
125
- res = "";
126
- timeout = 60;
127
- }
128
- if (!helper.isTrueEmpty(key)) {
129
- store.set(`${cacheName}:${key}`, JSON.stringify(res), timeout).catch(() => null);
130
- }
131
- else {
132
- store.set(cacheName, JSON.stringify(res), timeout).catch(() => null);
133
- }
134
- }
135
- return res;
136
- }
137
- else {
138
- // tslint:disable-next-line: no-invalid-this
139
- return value.apply(this, props);
140
- }
141
28
  }
142
- };
143
- // bind app_ready hook event
144
- bindSchedulerLockInit();
145
- return descriptor;
146
- };
29
+ });
30
+ }
31
+ n["default"] = e;
32
+ return Object.freeze(n);
147
33
  }
148
- exports.CacheAble = CacheAble;
149
- /**
150
- * bind scheduler lock init event
151
- *
152
- */
153
- const bindSchedulerLockInit = function () {
154
- const app = koatty_container_1.IOCContainer.getApp();
155
- app && app.once("appStart", async function () {
156
- await InitCacheStore(app);
157
- });
158
- };
159
- /**
160
- * Decorating the execution of this method will trigger a cache clear operation. Redis server config from db.ts.
161
- *
162
- * @export
163
- * @param {string} cacheName cacheName cache name
164
- * @param {(number | number[])} [paramKey] The index of the arguments.
165
- * @param {eventTimes} [eventTime="Before"]
166
- * @returns
167
- */
168
- function CacheEvict(cacheName, paramKey, eventTime = "Before") {
169
- return (target, methodName, descriptor) => {
170
- const componentType = koatty_container_1.IOCContainer.getType(target);
171
- if (componentType !== "SERVICE" && componentType !== "COMPONENT") {
172
- throw Error("This decorator only used in the service、component class.");
173
- }
174
- const identifier = koatty_container_1.IOCContainer.getIdentifier(target);
175
- const { value, configurable, enumerable } = descriptor;
176
- descriptor = {
177
- configurable,
178
- enumerable,
179
- writable: true,
180
- async value(...props) {
181
- let cacheFlag = true;
182
- const store = await GetCacheStore(this.app).catch(() => {
183
- cacheFlag = false;
184
- koatty_logger_1.DefaultLogger.Error("Get cache store instance failed.");
185
- return null;
186
- });
187
- if (cacheFlag) {
188
- let key = "";
189
- if (helper.isArray(paramKey)) {
190
- paramKey.map((it) => {
191
- if (!helper.isTrueEmpty(props[it])) {
192
- if (typeof props[it] === "object") {
193
- key = `${key}${helper.murmurHash(JSON.stringify(props[it]))}`;
194
- }
195
- else {
196
- key = `${key}${props[it] || ''}`;
197
- }
198
- }
199
- });
200
- }
201
- else if (helper.isNumber(paramKey)) {
202
- if (typeof props[paramKey] === "object") {
203
- key = helper.murmurHash(JSON.stringify(props[paramKey]));
204
- }
205
- else {
206
- key = props[paramKey] || "";
207
- }
208
- }
209
- else {
210
- key = `${identifier}:${methodName}`;
211
- }
212
- if (eventTime === "Before") {
213
- if (!helper.isTrueEmpty(key)) {
214
- await store.del(`${cacheName}:${key}`).catch(() => null);
215
- }
216
- else {
217
- await store.del(cacheName).catch(() => null);
218
- }
219
- // tslint:disable-next-line: no-invalid-this
220
- return value.apply(this, props);
221
- }
222
- else {
223
- // tslint:disable-next-line: no-invalid-this
224
- const res = await value.apply(this, props);
225
- if (!helper.isTrueEmpty(key)) {
226
- await store.del(`${cacheName}:${key}`).catch(() => null);
227
- }
228
- else {
229
- await store.del(cacheName).catch(() => null);
230
- }
231
- return res;
232
- }
233
- }
234
- else {
235
- // tslint:disable-next-line: no-invalid-this
236
- return value.apply(this, props);
237
- }
238
- }
239
- };
240
- return descriptor;
241
- };
34
+
35
+ var helper__namespace = /*#__PURE__*/_interopNamespace(helper);
36
+
37
+ /*
38
+ * @Author: richen
39
+ * @Date: 2020-07-06 19:53:43
40
+ * @LastEditTime: 2021-12-02 16:20:52
41
+ * @Description:
42
+ * @Copyright (c) - <richenlin(at)gmail.com>
43
+ */
44
+ // cacheStore
45
+ const cacheStore = {
46
+ store: null
47
+ };
48
+ /**
49
+ * get instances of cacheStore
50
+ *
51
+ * @export
52
+ * @param {Application} app
53
+ * @returns {*} {CacheStore}
54
+ */
55
+ async function GetCacheStore(app) {
56
+ var _a;
57
+ if (cacheStore.store && cacheStore.store.getConnection) {
58
+ return cacheStore.store;
59
+ }
60
+ const opt = (_a = app.config("CacheStore", "db")) !== null && _a !== void 0 ? _a : {};
61
+ if (helper__namespace.isEmpty(opt)) {
62
+ koatty_logger.DefaultLogger.Warn(`Missing CacheStore server configuration. Please write a configuration item with the key name 'CacheStore' in the db.ts file.`);
63
+ }
64
+ cacheStore.store = koatty_store.Store.getInstance(opt);
65
+ if (!helper__namespace.isFunction(cacheStore.store.getConnection)) {
66
+ throw Error(`CacheStore connection failed. `);
67
+ }
68
+ return cacheStore.store;
69
+ }
70
+ /**
71
+ * initiation CacheStore connection and client.
72
+ *
73
+ */
74
+ async function InitCacheStore() {
75
+ const app = koatty_container.IOCContainer.getApp();
76
+ app && app.once("appStart", async function () {
77
+ await GetCacheStore(app);
78
+ });
79
+ }
80
+ /**
81
+ * Decorate this method to support caching. Redis server config from db.ts.
82
+ * The cache method returns a value to ensure that the next time the method is executed with the same parameters,
83
+ * the results can be obtained directly from the cache without the need to execute the method again.
84
+ *
85
+ * @export
86
+ * @param {string} cacheName cache name
87
+ * @param {number} [timeout=3600] cache timeout
88
+ * @returns {MethodDecorator}
89
+ */
90
+ function CacheAble(cacheName, timeout = 3600) {
91
+ return (target, methodName, descriptor) => {
92
+ const componentType = koatty_container.IOCContainer.getType(target);
93
+ if (componentType !== "SERVICE" && componentType !== "COMPONENT") {
94
+ throw Error("This decorator only used in the service、component class.");
95
+ }
96
+ let identifier = koatty_container.IOCContainer.getIdentifier(target);
97
+ identifier = identifier || (target.constructor ? (target.constructor.name || "") : "");
98
+ const { value, configurable, enumerable } = descriptor;
99
+ descriptor = {
100
+ configurable,
101
+ enumerable,
102
+ writable: true,
103
+ async value(...props) {
104
+ let cacheFlag = true;
105
+ const store = await GetCacheStore(this.app).catch(() => {
106
+ cacheFlag = false;
107
+ koatty_logger.DefaultLogger.Error("Get cache store instance failed.");
108
+ return null;
109
+ });
110
+ if (cacheFlag) {
111
+ // tslint:disable-next-line: one-variable-per-declaration
112
+ let key = "", res;
113
+ if (props && props.length > 0) {
114
+ key = `${identifier}:${methodName}:${helper__namespace.murmurHash(JSON.stringify(props))}`;
115
+ }
116
+ else {
117
+ key = `${identifier}:${methodName}`;
118
+ }
119
+ res = await store.hget(cacheName, key).catch(() => null);
120
+ if (!helper__namespace.isEmpty(res)) {
121
+ return JSON.parse(res);
122
+ }
123
+ // tslint:disable-next-line: no-invalid-this
124
+ res = await value.apply(this, props);
125
+ // prevent cache penetration
126
+ if (helper__namespace.isEmpty(res)) {
127
+ res = "";
128
+ timeout = 60;
129
+ }
130
+ // async set store
131
+ store.hset(cacheName, key, JSON.stringify(res), timeout).catch(() => null);
132
+ return res;
133
+ }
134
+ else {
135
+ // tslint:disable-next-line: no-invalid-this
136
+ return value.apply(this, props);
137
+ }
138
+ }
139
+ };
140
+ // bind app_ready hook event
141
+ InitCacheStore();
142
+ return descriptor;
143
+ };
144
+ }
145
+ /**
146
+ * Decorating the execution of this method will trigger a cache clear operation. Redis server config from db.ts.
147
+ *
148
+ * @export
149
+ * @param {string} cacheName cacheName cache name
150
+ * @param {eventTimes} [eventTime="Before"]
151
+ * @returns
152
+ */
153
+ function CacheEvict(cacheName, eventTime = "Before") {
154
+ return (target, methodName, descriptor) => {
155
+ const componentType = koatty_container.IOCContainer.getType(target);
156
+ if (componentType !== "SERVICE" && componentType !== "COMPONENT") {
157
+ throw Error("This decorator only used in the service、component class.");
158
+ }
159
+ koatty_container.IOCContainer.getIdentifier(target);
160
+ const { value, configurable, enumerable } = descriptor;
161
+ descriptor = {
162
+ configurable,
163
+ enumerable,
164
+ writable: true,
165
+ async value(...props) {
166
+ let cacheFlag = true;
167
+ const store = await GetCacheStore(this.app).catch(() => {
168
+ cacheFlag = false;
169
+ koatty_logger.DefaultLogger.Error("Get cache store instance failed.");
170
+ return null;
171
+ });
172
+ if (cacheFlag) {
173
+ if (eventTime === "Before") {
174
+ await store.del(cacheName).catch(() => null);
175
+ // tslint:disable-next-line: no-invalid-this
176
+ return value.apply(this, props);
177
+ }
178
+ else {
179
+ // tslint:disable-next-line: no-invalid-this
180
+ const res = await value.apply(this, props);
181
+ store.del(cacheName).catch(() => null);
182
+ return res;
183
+ }
184
+ }
185
+ else {
186
+ // tslint:disable-next-line: no-invalid-this
187
+ return value.apply(this, props);
188
+ }
189
+ }
190
+ };
191
+ // bind app_ready hook event
192
+ InitCacheStore();
193
+ return descriptor;
194
+ };
242
195
  }
196
+
197
+ exports.CacheAble = CacheAble;
243
198
  exports.CacheEvict = CacheEvict;
244
- //# sourceMappingURL=index.js.map
199
+ exports.GetCacheStore = GetCacheStore;
package/dist/index.mjs ADDED
@@ -0,0 +1,173 @@
1
+ /*!
2
+ * @Author: richen
3
+ * @Date: 2022-05-27 11:35:38
4
+ * @License: BSD (3-Clause)
5
+ * @Copyright (c) - <richenlin(at)gmail.com>
6
+ * @HomePage: https://koatty.org/
7
+ */
8
+ import * as helper from 'koatty_lib';
9
+ import { DefaultLogger } from 'koatty_logger';
10
+ import { Store } from 'koatty_store';
11
+ import { IOCContainer } from 'koatty_container';
12
+
13
+ /*
14
+ * @Author: richen
15
+ * @Date: 2020-07-06 19:53:43
16
+ * @LastEditTime: 2021-12-02 16:20:52
17
+ * @Description:
18
+ * @Copyright (c) - <richenlin(at)gmail.com>
19
+ */
20
+ // cacheStore
21
+ const cacheStore = {
22
+ store: null
23
+ };
24
+ /**
25
+ * get instances of cacheStore
26
+ *
27
+ * @export
28
+ * @param {Application} app
29
+ * @returns {*} {CacheStore}
30
+ */
31
+ async function GetCacheStore(app) {
32
+ var _a;
33
+ if (cacheStore.store && cacheStore.store.getConnection) {
34
+ return cacheStore.store;
35
+ }
36
+ const opt = (_a = app.config("CacheStore", "db")) !== null && _a !== void 0 ? _a : {};
37
+ if (helper.isEmpty(opt)) {
38
+ DefaultLogger.Warn(`Missing CacheStore server configuration. Please write a configuration item with the key name 'CacheStore' in the db.ts file.`);
39
+ }
40
+ cacheStore.store = Store.getInstance(opt);
41
+ if (!helper.isFunction(cacheStore.store.getConnection)) {
42
+ throw Error(`CacheStore connection failed. `);
43
+ }
44
+ return cacheStore.store;
45
+ }
46
+ /**
47
+ * initiation CacheStore connection and client.
48
+ *
49
+ */
50
+ async function InitCacheStore() {
51
+ const app = IOCContainer.getApp();
52
+ app && app.once("appStart", async function () {
53
+ await GetCacheStore(app);
54
+ });
55
+ }
56
+ /**
57
+ * Decorate this method to support caching. Redis server config from db.ts.
58
+ * The cache method returns a value to ensure that the next time the method is executed with the same parameters,
59
+ * the results can be obtained directly from the cache without the need to execute the method again.
60
+ *
61
+ * @export
62
+ * @param {string} cacheName cache name
63
+ * @param {number} [timeout=3600] cache timeout
64
+ * @returns {MethodDecorator}
65
+ */
66
+ function CacheAble(cacheName, timeout = 3600) {
67
+ return (target, methodName, descriptor) => {
68
+ const componentType = IOCContainer.getType(target);
69
+ if (componentType !== "SERVICE" && componentType !== "COMPONENT") {
70
+ throw Error("This decorator only used in the service、component class.");
71
+ }
72
+ let identifier = IOCContainer.getIdentifier(target);
73
+ identifier = identifier || (target.constructor ? (target.constructor.name || "") : "");
74
+ const { value, configurable, enumerable } = descriptor;
75
+ descriptor = {
76
+ configurable,
77
+ enumerable,
78
+ writable: true,
79
+ async value(...props) {
80
+ let cacheFlag = true;
81
+ const store = await GetCacheStore(this.app).catch(() => {
82
+ cacheFlag = false;
83
+ DefaultLogger.Error("Get cache store instance failed.");
84
+ return null;
85
+ });
86
+ if (cacheFlag) {
87
+ // tslint:disable-next-line: one-variable-per-declaration
88
+ let key = "", res;
89
+ if (props && props.length > 0) {
90
+ key = `${identifier}:${methodName}:${helper.murmurHash(JSON.stringify(props))}`;
91
+ }
92
+ else {
93
+ key = `${identifier}:${methodName}`;
94
+ }
95
+ res = await store.hget(cacheName, key).catch(() => null);
96
+ if (!helper.isEmpty(res)) {
97
+ return JSON.parse(res);
98
+ }
99
+ // tslint:disable-next-line: no-invalid-this
100
+ res = await value.apply(this, props);
101
+ // prevent cache penetration
102
+ if (helper.isEmpty(res)) {
103
+ res = "";
104
+ timeout = 60;
105
+ }
106
+ // async set store
107
+ store.hset(cacheName, key, JSON.stringify(res), timeout).catch(() => null);
108
+ return res;
109
+ }
110
+ else {
111
+ // tslint:disable-next-line: no-invalid-this
112
+ return value.apply(this, props);
113
+ }
114
+ }
115
+ };
116
+ // bind app_ready hook event
117
+ InitCacheStore();
118
+ return descriptor;
119
+ };
120
+ }
121
+ /**
122
+ * Decorating the execution of this method will trigger a cache clear operation. Redis server config from db.ts.
123
+ *
124
+ * @export
125
+ * @param {string} cacheName cacheName cache name
126
+ * @param {eventTimes} [eventTime="Before"]
127
+ * @returns
128
+ */
129
+ function CacheEvict(cacheName, eventTime = "Before") {
130
+ return (target, methodName, descriptor) => {
131
+ const componentType = IOCContainer.getType(target);
132
+ if (componentType !== "SERVICE" && componentType !== "COMPONENT") {
133
+ throw Error("This decorator only used in the service、component class.");
134
+ }
135
+ IOCContainer.getIdentifier(target);
136
+ const { value, configurable, enumerable } = descriptor;
137
+ descriptor = {
138
+ configurable,
139
+ enumerable,
140
+ writable: true,
141
+ async value(...props) {
142
+ let cacheFlag = true;
143
+ const store = await GetCacheStore(this.app).catch(() => {
144
+ cacheFlag = false;
145
+ DefaultLogger.Error("Get cache store instance failed.");
146
+ return null;
147
+ });
148
+ if (cacheFlag) {
149
+ if (eventTime === "Before") {
150
+ await store.del(cacheName).catch(() => null);
151
+ // tslint:disable-next-line: no-invalid-this
152
+ return value.apply(this, props);
153
+ }
154
+ else {
155
+ // tslint:disable-next-line: no-invalid-this
156
+ const res = await value.apply(this, props);
157
+ store.del(cacheName).catch(() => null);
158
+ return res;
159
+ }
160
+ }
161
+ else {
162
+ // tslint:disable-next-line: no-invalid-this
163
+ return value.apply(this, props);
164
+ }
165
+ }
166
+ };
167
+ // bind app_ready hook event
168
+ InitCacheStore();
169
+ return descriptor;
170
+ };
171
+ }
172
+
173
+ export { CacheAble, CacheEvict, GetCacheStore };