@azteam/express 1.2.518 → 1.2.521

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.
@@ -16,21 +16,25 @@ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t =
16
16
  function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
17
17
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
18
18
  function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
19
+ var inFlightMap = new Map();
19
20
  function _default(key) {
20
21
  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
21
22
  var options = _objectSpread({
22
23
  ttl: 300,
23
- limitPage: 5
24
+ limitPage: 5,
25
+ singleFlight: true,
26
+ // Mặc định bật singleFlight cho cache
27
+ singleFlightTimeout: 15000
24
28
  }, opts);
25
29
  return /*#__PURE__*/function () {
26
30
  var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res, next) {
27
- var redis, cacheKey, cacheData;
31
+ var redis, cacheKey, cacheData, flightKey, flight, responseData, resolveFlight, rejectFlight, flightPromise, timer, cleanup, originalSuccess, originalError;
28
32
  return _regeneratorRuntime().wrap(function _callee$(_context) {
29
33
  while (1) switch (_context.prev = _context.next) {
30
34
  case 0:
31
35
  redis = req.redis;
32
36
  if (!redis) {
33
- _context.next = 18;
37
+ _context.next = 45;
34
38
  break;
35
39
  }
36
40
  cacheKey = typeof key === 'function' ? key(req) : key;
@@ -70,17 +74,113 @@ function _default(key) {
70
74
  case 16:
71
75
  return _context.abrupt("return", res.json(cacheData));
72
76
  case 17:
77
+ if (!(options.singleFlight && cacheKey)) {
78
+ _context.next = 44;
79
+ break;
80
+ }
81
+ flightKey = "flight:".concat(cacheKey);
82
+ if (!inFlightMap.has(flightKey)) {
83
+ _context.next = 34;
84
+ break;
85
+ }
86
+ flight = inFlightMap.get(flightKey);
87
+ _context.prev = 21;
88
+ _context.next = 24;
89
+ return flight;
90
+ case 24:
91
+ responseData = _context.sent;
92
+ if (!responseData) {
93
+ _context.next = 30;
94
+ break;
95
+ }
96
+ if (!(responseData.type === 'SUCCESS')) {
97
+ _context.next = 28;
98
+ break;
99
+ }
100
+ return _context.abrupt("return", res.json(responseData.resData));
101
+ case 28:
102
+ if (!(responseData.type === 'ERROR')) {
103
+ _context.next = 30;
104
+ break;
105
+ }
106
+ return _context.abrupt("return", res.error(responseData.errorCode || 'UNKNOWN', responseData.errors));
107
+ case 30:
108
+ _context.next = 34;
109
+ break;
110
+ case 32:
111
+ _context.prev = 32;
112
+ _context.t0 = _context["catch"](21);
113
+ case 34:
114
+ flightPromise = new Promise(function (resolve, reject) {
115
+ resolveFlight = resolve;
116
+ rejectFlight = reject;
117
+ });
118
+ timer = setTimeout(function () {
119
+ if (inFlightMap.has(flightKey)) {
120
+ inFlightMap["delete"](flightKey);
121
+ }
122
+ if (rejectFlight) {
123
+ rejectFlight(new Error('SingleFlight timeout'));
124
+ }
125
+ }, options.singleFlightTimeout || 15000);
126
+ inFlightMap.set(flightKey, flightPromise);
127
+ cleanup = function cleanup(result) {
128
+ clearTimeout(timer);
129
+ if (inFlightMap.has(flightKey)) {
130
+ inFlightMap["delete"](flightKey);
131
+ }
132
+ if (resolveFlight) {
133
+ resolveFlight(result);
134
+ }
135
+ }; // Lắng nghe sự kiện response kết thúc (finish/close) để dọn dẹp tuyệt đối kể cả khi handler bị crash ngoài ý muốn
136
+ res.once('finish', function () {
137
+ return cleanup(null);
138
+ });
139
+ res.once('close', function () {
140
+ return cleanup(null);
141
+ });
142
+
143
+ // Intercept res.success để lấy resData trước khi gửi đi
144
+ originalSuccess = res.success.bind(res);
145
+ originalError = res.error.bind(res);
146
+ res.success = function () {
147
+ var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
148
+ var guard = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
149
+ var allow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
150
+ // Gọi hàm gốc của res.success
151
+ var result = originalSuccess(data, guard, allow);
152
+ // Lấy lại dữ liệu cache chuẩn đã được build từ Server.js (resData)
153
+ cleanup({
154
+ type: 'SUCCESS',
155
+ resData: {
156
+ success: true,
157
+ data: data,
158
+ options: this.resOptions
159
+ }
160
+ });
161
+ return result;
162
+ };
163
+ res.error = function (code) {
164
+ var errors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
165
+ cleanup({
166
+ type: 'ERROR',
167
+ errorCode: code,
168
+ errors: errors
169
+ });
170
+ return originalError(code, errors);
171
+ };
172
+ case 44:
73
173
  res.cache = {
74
174
  key: cacheKey,
75
175
  ttl: options.ttl
76
176
  };
77
- case 18:
177
+ case 45:
78
178
  return _context.abrupt("return", next());
79
- case 19:
179
+ case 46:
80
180
  case "end":
81
181
  return _context.stop();
82
182
  }
83
- }, _callee);
183
+ }, _callee, null, [[21, 32]]);
84
184
  }));
85
185
  return function (_x, _x2, _x3) {
86
186
  return _ref.apply(this, arguments);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@azteam/express",
3
- "version": "1.2.518",
3
+ "version": "1.2.521",
4
4
  "license": "MIT",
5
5
  "author": "toda <sp.azsolution.net@gmail.com>",
6
6
  "main": "./lib/index.js",
@@ -1,10 +1,14 @@
1
1
  import _ from 'lodash';
2
2
  import qs from 'querystring';
3
3
 
4
+ const inFlightMap = new Map();
5
+
4
6
  export default function (key, opts = {}) {
5
7
  const options = {
6
8
  ttl: 300,
7
9
  limitPage: 5,
10
+ singleFlight: true, // Mặc định bật singleFlight cho cache
11
+ singleFlightTimeout: 15000,
8
12
  ...opts,
9
13
  };
10
14
 
@@ -23,6 +27,8 @@ export default function (key, opts = {}) {
23
27
  return next();
24
28
  }
25
29
  }
30
+
31
+ // 1. Kiểm tra Redis Cache (Cache Hit)
26
32
  const cacheData = await redis.get(cacheKey);
27
33
  if (cacheData) {
28
34
  if (!cacheData.success) {
@@ -31,6 +37,86 @@ export default function (key, opts = {}) {
31
37
 
32
38
  return res.json(cacheData);
33
39
  }
40
+
41
+ // 2. Cache Miss: Nếu bật singleFlight, kiểm tra xem có request nào cùng cacheKey đang chạy không
42
+ if (options.singleFlight && cacheKey) {
43
+ const flightKey = `flight:${cacheKey}`;
44
+
45
+ if (inFlightMap.has(flightKey)) {
46
+ const flight = inFlightMap.get(flightKey);
47
+ try {
48
+ const responseData = await flight;
49
+ if (responseData) {
50
+ if (responseData.type === 'SUCCESS') {
51
+ return res.json(responseData.resData);
52
+ }
53
+ if (responseData.type === 'ERROR') {
54
+ return res.error(responseData.errorCode || 'UNKNOWN', responseData.errors);
55
+ }
56
+ }
57
+ } catch (err) {
58
+ // Fallback nếu flight timeout/error thì cho request tự chạy tiếp
59
+ }
60
+ }
61
+
62
+ // Nếu chưa có ai bay -> Tạo flight mới
63
+ let resolveFlight;
64
+ let rejectFlight;
65
+ const flightPromise = new Promise((resolve, reject) => {
66
+ resolveFlight = resolve;
67
+ rejectFlight = reject;
68
+ });
69
+
70
+ const timer = setTimeout(() => {
71
+ if (inFlightMap.has(flightKey)) {
72
+ inFlightMap.delete(flightKey);
73
+ }
74
+ if (rejectFlight) {
75
+ rejectFlight(new Error('SingleFlight timeout'));
76
+ }
77
+ }, options.singleFlightTimeout || 15000);
78
+
79
+ inFlightMap.set(flightKey, flightPromise);
80
+
81
+ const cleanup = (result) => {
82
+ clearTimeout(timer);
83
+ if (inFlightMap.has(flightKey)) {
84
+ inFlightMap.delete(flightKey);
85
+ }
86
+ if (resolveFlight) {
87
+ resolveFlight(result);
88
+ }
89
+ };
90
+
91
+ // Lắng nghe sự kiện response kết thúc (finish/close) để dọn dẹp tuyệt đối kể cả khi handler bị crash ngoài ý muốn
92
+ res.once('finish', () => cleanup(null));
93
+ res.once('close', () => cleanup(null));
94
+
95
+ // Intercept res.success để lấy resData trước khi gửi đi
96
+ const originalSuccess = res.success.bind(res);
97
+ const originalError = res.error.bind(res);
98
+
99
+ res.success = function (data = {}, guard = [], allow = []) {
100
+ // Gọi hàm gốc của res.success
101
+ const result = originalSuccess(data, guard, allow);
102
+ // Lấy lại dữ liệu cache chuẩn đã được build từ Server.js (resData)
103
+ cleanup({
104
+ type: 'SUCCESS',
105
+ resData: {
106
+ success: true,
107
+ data,
108
+ options: this.resOptions,
109
+ },
110
+ });
111
+ return result;
112
+ };
113
+
114
+ res.error = function (code, errors = []) {
115
+ cleanup({type: 'ERROR', errorCode: code, errors});
116
+ return originalError(code, errors);
117
+ };
118
+ }
119
+
34
120
  res.cache = {
35
121
  key: cacheKey,
36
122
  ttl: options.ttl,
@@ -11,5 +11,3 @@ export {default as verifyGoogleAppMiddleware} from './verifyGoogleAppMiddleware'
11
11
  export {default as recaptchaMiddleware} from './recaptchaMiddleware';
12
12
  export {default as uploadMiddleware} from './uploadMiddleware';
13
13
  export * from './abortMiddleware';
14
-
15
-