@ad-execute-manager/helper 2.0.0-alpha.2 → 2.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.
Files changed (2) hide show
  1. package/README.md +453 -115
  2. package/package.json +2 -2
package/README.md CHANGED
@@ -1,115 +1,453 @@
1
- # @singcl/helper
2
-
3
- A collection of utility helper classes for JavaScript applications including EventEmitter, Logger, Storage, CountRecorder, PubSub, and SerializableError.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- npm install @singcl/helper
9
- ```
10
-
11
- ## Features
12
-
13
- - **EventEmitter**: A powerful event emitter with support for once events, max listeners, and event queuing
14
- - **Logger**: A flexible logging utility with multiple log levels and customizable prefixes
15
- - **Storage**: A storage wrapper with expiration support, including "today" expiration for daily data
16
- - **CountRecorder**: A utility for tracking and managing counts with expiration
17
- - **PubSub**: A simple publish-subscribe pattern implementation
18
- - **SerializableError**: An error class that can be serialized to JSON
19
-
20
- ## Usage
21
-
22
- ### EventEmitter
23
-
24
- ```javascript
25
- import { EventEmitter } from '@singcl/helper';
26
-
27
- const emitter = new EventEmitter({ maxListeners: 10 });
28
-
29
- emitter.on('event', (data) => {
30
- console.log('Received:', data);
31
- });
32
-
33
- emitter.emit('event', { message: 'Hello' });
34
- ```
35
-
36
- ### Logger
37
-
38
- ```javascript
39
- import { Logger } from '@singcl/helper';
40
-
41
- const logger = new Logger({ prefix: 'MyApp', level: 'info' });
42
-
43
- logger.info('Application started');
44
- logger.error('Something went wrong');
45
- ```
46
-
47
- ### Storage
48
-
49
- ```javascript
50
- import { Storage } from '@singcl/helper';
51
-
52
- const storage = new Storage({ prefix: 'myapp_' });
53
-
54
- // Set data that expires at end of day
55
- storage.setItem('dailyTask', { completed: false }, 'today');
56
-
57
- // Set data with custom expiration (2 hours)
58
- storage.setItem('tempData', { value: 123 }, 2 * 60 * 60 * 1000);
59
-
60
- // Get data
61
- const data = storage.getItem('dailyTask');
62
- ```
63
-
64
- ### CountRecorder
65
-
66
- ```javascript
67
- import { CountRecorder } from '@singcl/helper';
68
-
69
- const recorder = CountRecorder.new({
70
- local_sign: 'daily_ads',
71
- total: 5,
72
- expire: 'today',
73
- userId: 'user123'
74
- });
75
-
76
- console.log(recorder.remain()); // Remaining count
77
- recorder.updateToday(); // Increment today's count
78
- ```
79
-
80
- ### PubSub
81
-
82
- ```javascript
83
- import { PubSub } from '@singcl/helper';
84
-
85
- const pubsub = new PubSub();
86
-
87
- const unsubscribe = pubsub.on('topic', (data) => {
88
- console.log('Received:', data);
89
- });
90
-
91
- pubsub.emit('topic', { message: 'Hello' });
92
-
93
- unsubscribe();
94
- ```
95
-
96
- ### SerializableError
97
-
98
- ```javascript
99
- import { SerializableError } from '@singcl/helper';
100
-
101
- const error = new SerializableError('Something went wrong', {
102
- errorCode: 500,
103
- errMsg: 'Internal server error'
104
- });
105
-
106
- console.log(error.toJSON());
107
- ```
108
-
109
- ## API
110
-
111
- See individual class documentation for detailed API information.
112
-
113
- ## License
114
-
115
- MIT
1
+ # @ad-execute-manager/helper
2
+
3
+ A collection of utility helper classes for JavaScript applications including EventEmitter, Logger, Storage, CountRecorder, PubSub, and SerializableError.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @ad-execute-manager/helper
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **EventEmitter**: A powerful event emitter with support for once events, max listeners, and event queuing
14
+ - **Logger**: A flexible logging utility with multiple log levels and customizable prefixes
15
+ - **Storage**: A storage wrapper with expiration support, including "today" expiration for daily data
16
+ - **CountRecorder**: A utility for tracking and managing counts with expiration
17
+ - **PubSub**: A simple publish-subscribe pattern implementation
18
+ - **SerializableError**: An error class that can be serialized to JSON
19
+
20
+ ## Usage
21
+
22
+ ### EventEmitter
23
+
24
+ ```javascript
25
+ import { EventEmitter } from '@ad-execute-manager/helper';
26
+
27
+ const emitter = new EventEmitter({ maxListeners: 10 });
28
+
29
+ emitter.on('event', (data) => {
30
+ console.log('Received:', data);
31
+ });
32
+
33
+ emitter.emit('event', { message: 'Hello' });
34
+ ```
35
+
36
+ ### Logger
37
+
38
+ ```javascript
39
+ import { Logger } from '@ad-execute-manager/helper';
40
+
41
+ const logger = new Logger({ prefix: 'MyApp', level: 'info' });
42
+
43
+ logger.info('Application started');
44
+ logger.error('Something went wrong');
45
+ ```
46
+
47
+ ### Storage
48
+
49
+ ```javascript
50
+ import { Storage } from '@ad-execute-manager/helper';
51
+
52
+ const storage = new Storage({ prefix: 'myapp_' });
53
+
54
+ // Set data that expires at end of day
55
+ storage.setItem('dailyTask', { completed: false }, 'today');
56
+
57
+ // Set data with custom expiration (2 hours)
58
+ storage.setItem('tempData', { value: 123 }, 2 * 60 * 60 * 1000);
59
+
60
+ // Get data
61
+ const data = storage.getItem('dailyTask');
62
+ ```
63
+
64
+ ### CountRecorder
65
+
66
+ ```javascript
67
+ import { CountRecorder } from '@ad-execute-manager/helper';
68
+
69
+ const recorder = CountRecorder.new({
70
+ local_sign: 'daily_ads',
71
+ total: 5,
72
+ expire: 'today',
73
+ userId: 'user123'
74
+ });
75
+
76
+ console.log(recorder.remain()); // Remaining count
77
+ recorder.updateToday(); // Increment today's count
78
+ ```
79
+
80
+ ### PubSub
81
+
82
+ ```javascript
83
+ import { PubSub } from '@ad-execute-manager/helper';
84
+
85
+ const pubsub = new PubSub();
86
+
87
+ const unsubscribe = pubsub.on('topic', (data) => {
88
+ console.log('Received:', data);
89
+ });
90
+
91
+ pubsub.emit('topic', { message: 'Hello' });
92
+
93
+ unsubscribe();
94
+ ```
95
+
96
+ ### SerializableError
97
+
98
+ ```javascript
99
+ import { SerializableError } from '@ad-execute-manager/helper';
100
+
101
+ const error = new SerializableError('Something went wrong', {
102
+ errorCode: 500,
103
+ errMsg: 'Internal server error'
104
+ });
105
+
106
+ console.log(error.toJSON());
107
+ ```
108
+
109
+ ## Examples
110
+
111
+ ### 实际应用场景示例
112
+
113
+ #### 1. 应用状态管理
114
+
115
+ ```javascript
116
+ import { EventEmitter } from '@ad-execute-manager/helper';
117
+
118
+ // 创建一个全局事件总线
119
+ const eventBus = new EventEmitter();
120
+
121
+ // 组件 A 订阅状态更新
122
+ eventBus.on('userLoggedIn', (userData) => {
123
+ console.log('User logged in:', userData);
124
+ // 更新组件状态
125
+ });
126
+
127
+ // 组件 B 触发登录事件
128
+ function handleLogin(userData) {
129
+ // 登录逻辑
130
+ eventBus.emit('userLoggedIn', userData);
131
+ }
132
+ ```
133
+
134
+ #### 2. 应用配置管理
135
+
136
+ ```javascript
137
+ import Storage from '@ad-execute-manager/helper';
138
+
139
+ // 创建配置存储
140
+ const configStorage = Storage.new({ prefix: 'app_config_' });
141
+
142
+ // 保存用户偏好设置
143
+ function saveUserPreferences(preferences) {
144
+ configStorage.setItem('userPreferences', preferences);
145
+ }
146
+
147
+ // 获取用户偏好设置
148
+ function getUserPreferences() {
149
+ return configStorage.getItem('userPreferences') || {
150
+ theme: 'light',
151
+ notifications: true
152
+ };
153
+ }
154
+ ```
155
+
156
+ #### 3. 广告展示次数限制
157
+
158
+ ```javascript
159
+ import { CountRecorder } from '@ad-execute-manager/helper';
160
+
161
+ // 创建广告计数器
162
+ const adCounter = CountRecorder.new({
163
+ local_sign: 'daily_ads',
164
+ total: 5, // 每天最多展示 5 次
165
+ expire: 'today',
166
+ userId: 'user123'
167
+ });
168
+
169
+ // 检查是否可以展示广告
170
+ function canShowAd() {
171
+ return adCounter.remain() > 0;
172
+ }
173
+
174
+ // 展示广告并更新计数
175
+ function showAd() {
176
+ if (canShowAd()) {
177
+ console.log('Showing ad...');
178
+ adCounter.updateToday();
179
+ return true;
180
+ } else {
181
+ console.log('Ad limit reached for today');
182
+ return false;
183
+ }
184
+ }
185
+ ```
186
+
187
+ #### 4. 应用日志系统
188
+
189
+ ```javascript
190
+ import { Logger } from '@ad-execute-manager/helper';
191
+
192
+ // 创建应用日志器
193
+ const appLogger = new Logger({
194
+ prefix: 'MyApp',
195
+ level: process.env.NODE_ENV === 'production' ? 'info' : 'debug'
196
+ });
197
+
198
+ // 记录应用启动
199
+ appLogger.info('Application started');
200
+
201
+ // 记录错误
202
+ function handleError(error) {
203
+ appLogger.error('Error occurred:', error);
204
+ // 错误处理逻辑
205
+ }
206
+ ```
207
+
208
+ #### 5. 微服务间通信
209
+
210
+ ```javascript
211
+ import PubSub from '@ad-execute-manager/helper';
212
+
213
+ // 创建消息总线
214
+ const messageBus = new PubSub();
215
+
216
+ // 服务 A 订阅消息
217
+ messageBus.on('orderCreated', (orderData) => {
218
+ console.log('Processing order:', orderData.id);
219
+ // 处理订单逻辑
220
+ });
221
+
222
+ // 服务 B 发布消息
223
+ function createOrder(orderData) {
224
+ // 创建订单逻辑
225
+ messageBus.emit('orderCreated', orderData);
226
+ }
227
+ ```
228
+
229
+ #### 6. 错误处理与序列化
230
+
231
+ ```javascript
232
+ import { SerializableError } from '@ad-execute-manager/helper';
233
+
234
+ // 处理 API 错误
235
+ async function fetchData() {
236
+ try {
237
+ const response = await fetch('/api/data');
238
+ if (!response.ok) {
239
+ throw new SerializableError('API request failed', {
240
+ errorCode: response.status,
241
+ errMsg: response.statusText
242
+ });
243
+ }
244
+ return await response.json();
245
+ } catch (error) {
246
+ if (error instanceof SerializableError) {
247
+ // 序列化错误以便传输
248
+ console.log('Serialized error:', error.toJSON());
249
+ // 发送错误到监控系统
250
+ }
251
+ throw error;
252
+ }
253
+ }
254
+ ```
255
+
256
+ ## API
257
+
258
+ ### EventEmitter
259
+
260
+ #### Constructor
261
+
262
+ ```javascript
263
+ new EventEmitter(options)
264
+ ```
265
+
266
+ - **options** (Object): 配置选项
267
+ - **maxListeners** (Number): 最大监听器数量,默认 5
268
+ - **maxQueueSize** (Number): 最大队列大小,默认 1
269
+ - **maxOnceEvents** (Number): 最大一次性事件数量,默认 5
270
+
271
+ #### Methods
272
+
273
+ - **on(event, listener)**
274
+ - **event** (String): 事件名称
275
+ - **listener** (Function): 事件监听器函数
276
+ - 注册一个事件监听器
277
+
278
+ - **once(event, listener)**
279
+ - **event** (String): 事件名称
280
+ - **listener** (Function): 事件监听器函数
281
+ - 注册一个只执行一次的事件监听器
282
+
283
+ - **emit(event, ...args)**
284
+ - **event** (String): 事件名称
285
+ - **...args** (Any): 传递给监听器的参数
286
+ - 触发一个事件
287
+
288
+ - **off(event, listenerToRemove)**
289
+ - **event** (String): 事件名称
290
+ - **listenerToRemove** (Function): 要移除的监听器函数
291
+ - 移除一个事件监听器
292
+
293
+ - **removeAllListeners(event)**
294
+ - **event** (String, optional): 事件名称,不提供则移除所有事件的监听器
295
+ - 移除所有事件监听器
296
+
297
+ - **static geInstance(args)**
298
+ - **args** (Object): 构造函数参数
299
+ - 返回 EventEmitter 的单例实例
300
+
301
+ ### Logger
302
+
303
+ #### Constructor
304
+
305
+ ```javascript
306
+ new Logger(options)
307
+ ```
308
+
309
+ - **options** (Object): 配置选项
310
+ - **prefix** (String): 日志前缀,默认 'Logger'
311
+ - **level** (String): 日志级别,可选值: 'error', 'warn', 'info', 'log', 'debug',默认 'log'
312
+ - **enabled** (Boolean): 是否启用日志,默认 true
313
+
314
+ #### Methods
315
+
316
+ - **enable()**: 启用日志
317
+ - **disable()**: 禁用日志
318
+ - **isEnabled()**: 返回日志是否启用
319
+ - **setLevel(level)**: 设置日志级别
320
+ - **level** (String): 日志级别
321
+ - **error(message, ...args)**: 输出错误日志
322
+ - **warn(message, ...args)**: 输出警告日志
323
+ - **info(message, ...args)**: 输出信息日志
324
+ - **log(message, ...args)**: 输出普通日志
325
+ - **debug(message, ...args)**: 输出调试日志
326
+
327
+ ### Storage
328
+
329
+ #### Constructor
330
+
331
+ ```javascript
332
+ new Storage(options)
333
+ ```
334
+
335
+ - **options** (Object): 配置选项
336
+ - **prefix** (String): 存储键前缀,默认 'storage_'
337
+ - **expire** (Number|null): 默认过期时间(毫秒),null 表示永不过期
338
+ - **userId** (String|Number): 用户 ID
339
+
340
+ #### Methods
341
+
342
+ - **setItem(key, value, expire)**
343
+ - **key** (String): 存储键
344
+ - **value** (Any): 存储值
345
+ - **expire** (Number|'today', optional): 过期时间(毫秒)或 'today' 表示当天有效
346
+ - 设置存储项
347
+
348
+ - **getItem(key)**
349
+ - **key** (String): 存储键
350
+ - 返回存储的值,如果过期或不存在则返回 null
351
+
352
+ - **getUserItem(key)**
353
+ - **key** (String): 存储键
354
+ - 返回用户维度的存储值,如果过期或不存在则返回 null
355
+
356
+ - **setUserItem(key, value, expire)**
357
+ - **key** (String): 存储键
358
+ - **value** (Any): 存储值
359
+ - **expire** (Number|'today', optional): 过期时间(毫秒)或 'today' 表示当天有效
360
+ - 设置用户维度的存储项
361
+
362
+ - **removeItem(key)**
363
+ - **key** (String): 存储键
364
+ - 删除存储项
365
+
366
+ - **clear()**: 清空所有存储项
367
+
368
+ - **keys()**: 返回所有未过期的存储键数组
369
+
370
+ - **static new(args)**
371
+ - **args** (Object): 构造函数参数
372
+ - 返回 Storage 的新实例
373
+
374
+ ### CountRecorder
375
+
376
+ #### Constructor
377
+
378
+ ```javascript
379
+ new CountRecorder(args)
380
+ ```
381
+
382
+ - **args** (Object): 配置选项
383
+ - **local_sign** (String): 本地存储标识
384
+ - **total** (Number, optional): 总次数
385
+ - **expire** (Number|'today', optional): 过期时间(毫秒)或 'today' 表示当天有效
386
+ - **userId** (String|Number): 用户 ID
387
+
388
+ #### Methods
389
+
390
+ - **updateToday()**: 更新当天计数
391
+
392
+ - **remain()**: 返回剩余次数
393
+
394
+ - **static new(args)**
395
+ - **args** (Object): 构造函数参数
396
+ - 返回 CountRecorder 的新实例
397
+
398
+ ### PubSub
399
+
400
+ #### Constructor
401
+
402
+ ```javascript
403
+ new PubSub()
404
+ ```
405
+
406
+ #### Methods
407
+
408
+ - **on(eventName, callback)**
409
+ - **eventName** (String): 事件名称
410
+ - **callback** (Function): 事件回调函数
411
+ - 注册一个事件监听器,返回一个取消订阅函数
412
+
413
+ - **off(eventName, callback)**
414
+ - **eventName** (String): 事件名称
415
+ - **callback** (Function): 要移除的回调函数
416
+ - 移除一个事件监听器
417
+
418
+ - **emit(eventName, ...args)**
419
+ - **eventName** (String): 事件名称
420
+ - **...args** (Any): 传递给回调的参数
421
+ - 触发一个事件
422
+
423
+ - **once(eventName, callback)**
424
+ - **eventName** (String): 事件名称
425
+ - **callback** (Function): 事件回调函数
426
+ - 注册一个只执行一次的事件监听器
427
+
428
+ - **listenerCount(eventName)**
429
+ - **eventName** (String): 事件名称
430
+ - 返回事件的监听器数量
431
+
432
+ - **removeAllListeners()**: 移除所有事件监听器
433
+
434
+ ### SerializableError
435
+
436
+ #### Constructor
437
+
438
+ ```javascript
439
+ new SerializableError(message, options)
440
+ ```
441
+
442
+ - **message** (String): 错误消息
443
+ - **options** (Object, optional): 配置选项
444
+ - **errMsg** (String): 错误描述
445
+ - **errorCode** (Number): 错误代码
446
+
447
+ #### Methods
448
+
449
+ - **toJSON()**: 返回可序列化的错误对象
450
+
451
+ ## License
452
+
453
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ad-execute-manager/helper",
3
- "version": "2.0.0-alpha.2",
3
+ "version": "2.0.0",
4
4
  "description": "A collection of utility helper classes for JavaScript applications including EventEmitter, Logger, Storage, CountRecorder, PubSub, and SerializableError.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -21,7 +21,7 @@
21
21
  "url": "https://github.com/singcl"
22
22
  },
23
23
  "license": "MIT",
24
- "homepage": "https://npmjs.com/package/@singcl/helper",
24
+ "homepage": "https://npmjs.com/package/@ad-execute-manager/helper",
25
25
  "repository": {
26
26
  "type": "git",
27
27
  "url": "git+https://github.com/singcl/ad-execute-manager.git"