memory-sri 1.0.3 → 1.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Santipap Eiamsamlee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,96 +1,128 @@
1
- # Memory Library
2
-
3
- A simple and customizable memory data utility for Node.js.
4
-
5
- ## Installation
6
-
7
- You can install this package using NPM:
8
-
9
- ```bash
10
- npm install memory-sri
11
- ```
12
-
13
- ## import memory-sri
14
- ```bash
15
- import Memory from 'memory-sri';
16
- ```
17
-
18
- ### OR
19
- ```bash
20
- const Memory = require('memory-sri');
21
- ```
22
-
23
- ## Example of Full Usage:
24
- ### function has three parameters: Identifier, Data, Expire
25
- Memory.set('1', "a1", 10);
26
- // Key '1', Value "a1", Expires in 10 seconds
27
-
28
- Memory.set('2', { b: 2 }, 20);
29
- // Key '2', Value is an object, Expires in 20 seconds
30
-
31
- Memory.set('3', [ "a1", "a2" ], 30);
32
- // Key '3', Value is an array of strings, Expires in 30 seconds
33
-
34
- Memory.set('4', [ { a: "a1", b: "b1" } ], 40);
35
- // Key '4', Value is an array of objects, Expires in 40 seconds
36
-
37
- Memory.set('5', "not set expire");
38
- // Data will expire in 12 hours.
39
-
40
-
41
- #### set
42
- ```bash
43
- Memory.set('1', "a1", 10);
44
- Memory.set('2', { b: 2 }, 20);
45
- Memory.set('3', [ "a1", "a2" ], 30);
46
- Memory.set('4', [ { a: "a1", b: "b1" } ], 40);
47
- Memory.set('5', "not set expire");
48
- ```
49
-
50
- #### get
51
- ```bash
52
- let test1 = Memory.get(1); // "a1"
53
- let test2 = Memory.get(2); // { b: 2 }
54
- let test3 = Memory.get(3); // [ "a1", "a2" ]
55
- let test4 = Memory.get(4); // [ { a: "a1", b: "b1" } ]
56
- ```
57
-
58
- #### get timeout
59
- ```bash
60
- let test1 = Memory.ttl(1); // 10000
61
- ```
62
-
63
- #### multiple
64
- ```bash
65
- let test1 = Memory.multiple();
66
- ```
67
-
68
- ### Output:
69
- ```bash
70
- [
71
- { id: "1", data: "a1" },
72
- { id: "2", data: { b: 2 } },
73
- { id: "3", data: [ "a1", "a2" ] },
74
- { id: "4", data: [ { a: "a1", b: "b1" } ] }
75
- ]
76
- ```
77
-
78
- #### delete
79
- ```bash
80
- Memory.del(1);
81
- ```
82
-
83
- #### delete all
84
- ```bash
85
- Memory.delall();
86
- ```
87
-
88
- ### Key Features:
89
- - **Installation**: Instructions on how to install the package with NPM.
90
- - **Usage**: Detailed steps on how to import and use the `memory-sri` library in your application.
91
- - **Lightweight In-Memory Storage**: Store strings, objects, arrays, or nested structures with minimal overhead.
92
- - **Simple function**: Provides set, get, ttl, multiple, del, and delall for easy data handling.
93
- - **Automatic Expiry Support**: Each key can have an expiration time (TTL) in seconds.
94
- - **Flexible Data Types**: Supports strings, objects, arrays, and complex nested data.
95
- - **Batch Retrieval**: multiple() method returns all stored data in a clean array format.
96
- - **Easy Integration**: Works with both CommonJS (require) and ES Modules (import).
1
+ # Memory Library
2
+
3
+ A simple and customizable memory data utility for Node.js.
4
+
5
+ ## Installation
6
+
7
+ You can install this package using NPM:
8
+
9
+ ```bash
10
+ npm install memory-sri
11
+ ```
12
+
13
+ ## import memory-sri
14
+ ```bash
15
+ import Memory from 'memory-sri';
16
+ ```
17
+
18
+ ### OR
19
+ ```bash
20
+ const Memory = require('memory-sri');
21
+ ```
22
+
23
+ ## Example of Full Usage:
24
+ ### function has three parameters: Identifier, Data, Expire
25
+ Memory.set('1', "a1", 10);
26
+ // Key '1', Value "a1", Expires in 10 seconds
27
+
28
+ Memory.set('2', { b: 2 }, 20);
29
+ // Key '2', Value is an object, Expires in 20 seconds
30
+
31
+ Memory.set('3', [ "a1", "a2" ], 30);
32
+ // Key '3', Value is an array of strings, Expires in 30 seconds
33
+
34
+ Memory.set('4', [ { a: "a1", b: "b1" } ], 40);
35
+ // Key '4', Value is an array of objects, Expires in 40 seconds
36
+
37
+ Memory.set('5', "not set expire");
38
+ // If no expiration time is set, the data will automatically expire after 3 days or 259200 seconds.
39
+ // Maximum 7 days or 604800 seconds.
40
+
41
+
42
+ #### set
43
+ ```bash
44
+ Memory.set('1', "a1", 10);
45
+ Memory.set('2', { b: 2 }, 20);
46
+ Memory.set('3', [ "a1", "a2" ], 30);
47
+ Memory.set('4', [ { a: "a1", b: "b1" } ], 40);
48
+ Memory.set('5', "not set expire");
49
+ ```
50
+
51
+ #### get
52
+ ```bash
53
+ let test1 = Memory.get(1); // "a1"
54
+ let test2 = Memory.get(2); // { b: 2 }
55
+ let test3 = Memory.get(3); // [ "a1", "a2" ]
56
+ let test4 = Memory.get(4); // [ { a: "a1", b: "b1" } ]
57
+ ```
58
+
59
+ #### get timeout
60
+ ```bash
61
+ let test1 = Memory.ttl(1); // 10000
62
+ ```
63
+
64
+ #### multiple
65
+ ```bash
66
+ let test1 = Memory.multiple();
67
+ ```
68
+
69
+ ### Output:
70
+ ```bash
71
+ [
72
+ { id: "1", data: "a1" },
73
+ { id: "2", data: { b: 2 } },
74
+ { id: "3", data: [ "a1", "a2" ] },
75
+ { id: "4", data: [ { a: "a1", b: "b1" } ] }
76
+ ]
77
+ ```
78
+
79
+ #### delete
80
+ ```bash
81
+ Memory.del(1);
82
+ ```
83
+
84
+ #### delete all
85
+ ```bash
86
+ Memory.delall();
87
+ ```
88
+
89
+ ### Task
90
+ #### Task function
91
+ ```bash
92
+ const plus = function(a, b){
93
+ return a + b;
94
+ }
95
+ ```
96
+
97
+ #### Task usage
98
+ ```bash
99
+ // "test" is name of task
100
+ // { user: 1 } is data send to task
101
+ // retry 3 time, maximum 5 time
102
+ Task.addtask("test", { user: 1 }, 3);
103
+ ```
104
+
105
+ ```bash
106
+ Task.runtask("test", async function () {
107
+ console.log("Running with data:", this.data);
108
+ let a = 1;
109
+ let b = 2;
110
+ let c = plus(a, b);
111
+ console.log(`result: ${c}`);
112
+ });
113
+ ```
114
+
115
+ ### Key Features:
116
+ - **Installation**: Instructions on how to install the package with NPM.
117
+ - **Usage**: Detailed steps on how to import and use the `memory-sri` library in your application.
118
+ - **Lightweight In-Memory Storage**: Store strings, objects, arrays, or nested structures with minimal overhead.
119
+ - **Simple function**: Provides set, get, ttl, multiple, del, and delall for easy data handling.
120
+ - **Automatic Expiry Support**: Each key can have an expiration time (TTL) in seconds.
121
+ - **Flexible Data Types**: Supports strings, objects, arrays, and complex nested data.
122
+ - **Batch Retrieval**: multiple() method returns all stored data in a clean array format.
123
+ - **Easy Integration**: Works with both CommonJS (require) and ES Modules (import).
124
+
125
+ ### New Features:
126
+ - **Background Task Processing**: A separate worker process reads tasks from the queue and runs the function.
127
+
128
+ - **Test jest**: Jest tests verify core functionality, TTL sorting, and correct task recording.
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export function get(identifier: string): any;
2
+ export function ttl(identifier: string): any;
3
+ export function multiple(): any;
4
+ export function set(identifier: string, data?: any, time?: number): any;
5
+ export function del(identifier: string): any;
6
+ export function delall(): any;
7
+ export function addtask(name?: any, data?: any, retries?: any): any;
8
+ export function runtask(name?: any, taskFn?: any): any;
package/index.js CHANGED
@@ -1,34 +1,17 @@
1
- const Memory = require("./src/memory");
2
-
3
- function getSearch(identifier = "a501cf48-9e8a-497e-a158-f87081503425") {
4
- return Memory.get(identifier);
5
- }
6
-
7
- function getDataAll() {
8
- return Memory.multiple();
9
- }
10
-
11
- function getTimeout(identifier = "a501cf48-9e8a-497e-a158-f87081503425") {
12
- return Memory.ttl(identifier);
13
- }
14
-
15
- function setFormat(identifier, data = [], time = 43200) {
16
- Memory.set(identifier, data, time);
17
- }
18
-
19
- function delData(identifier = "a501cf48-9e8a-497e-a158-f87081503425") {
20
- return Memory.del(identifier);
21
- }
22
-
23
- function delAll() {
24
- return Memory.delall();
25
- }
26
-
27
- module.exports = {
28
- set: setFormat,
29
- get: getSearch,
30
- del: delData,
31
- delall: delAll,
32
- ttl: getTimeout,
33
- multiple: getDataAll,
34
- };
1
+ const Task = require("./lib/main");
2
+
3
+ const plus = function (a, b) {
4
+ return a + b;
5
+ };
6
+
7
+ Task.addtask("test", { user: 1 }, 3);
8
+
9
+ Task.runtask("test", async function () {
10
+ console.log("Running with data:", this.data);
11
+ let a = 1;
12
+ let b = 2;
13
+ let c = plus(a, b);
14
+ console.log(`result: ${c}`);
15
+ });
16
+
17
+ module.exports = Task;
package/lib/main.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * module dependencies
3
+ */
4
+ const Memory = require("./memory");
5
+ const Task = require("./worker");
6
+
7
+ /**
8
+ * expose object
9
+ */
10
+ let memory = module.exports;
11
+
12
+ /**
13
+ * version
14
+ */
15
+ memory.version = "1.1.11";
16
+
17
+ /**
18
+ * Memory
19
+ *
20
+ * @param {String} identifier
21
+ * @param {Number} time
22
+ * @param {Object} [data]
23
+ * @api public
24
+ */
25
+ memory.get = function getSearch(
26
+ identifier = "a501cf48-9e8a-497e-a158-f87081503425"
27
+ ) {
28
+ return Memory.get(identifier);
29
+ };
30
+
31
+ memory.ttl = function getTimeout(
32
+ identifier = "a501cf48-9e8a-497e-a158-f87081503425"
33
+ ) {
34
+ return Memory.ttl(identifier);
35
+ };
36
+
37
+ memory.multiple = function getDataAll() {
38
+ return Memory.multiple();
39
+ };
40
+
41
+ memory.set = function setData(identifier, data = [], time = 259200) {
42
+ const MAX_TTL = 604800;
43
+ const limittime = Math.min(time, MAX_TTL);
44
+ return Worker.addTask(setTask(identifier, data, limittime), data);
45
+ };
46
+
47
+ memory.del = function delData(
48
+ identifier = "a501cf48-9e8a-497e-a158-f87081503425"
49
+ ) {
50
+ return Worker.addTask(delTask(identifier), identifier);
51
+ };
52
+
53
+ memory.delall = function delAllData() {
54
+ return Worker.addTask(delAllTask(), "Delete All");
55
+ };
56
+
57
+ /**
58
+ * Worker
59
+ *
60
+ * @param {Fuction} taskFn
61
+ * @param {Object} [args]
62
+ * @api public
63
+ */
64
+
65
+ memory.addtask = Task.addTask;
66
+ memory.runtask = Task.runTask;
67
+
68
+ /**
69
+ * private util functions
70
+ */
71
+
72
+ function setTask(identifier, data, time) {
73
+ return () => Memory.set(identifier, data, time);
74
+ }
75
+
76
+ function delTask(identifier) {
77
+ return () => Memory.del(identifier);
78
+ }
79
+
80
+ function delAllTask() {
81
+ return () => Memory.delall();
82
+ }
@@ -1,83 +1,96 @@
1
- const attemptsStore = {};
2
-
3
- /* save data */
4
- function recordAttempt(identifier, data, timeoutSeconds) {
5
- const now = Date.now();
6
- const expiryTime = now + timeoutSeconds * 1000;
7
- const elapsed = expiryTime - now;
8
- const entry = { time: expiryTime, data, ttl: elapsed };
9
- attemptsStore[identifier] = entry;
10
- return entry;
11
- }
1
+ /**
2
+ * expose object
3
+ */
4
+ let Memory = module.exports;
12
5
 
13
- /* validate timeout */
14
- function getRemainingTime(identifier) {
15
- const entry = attemptsStore[identifier];
16
- if (!entry) return 0;
17
- const now = Date.now();
18
- const elapsed = entry.time - now;
19
- const entryID = { time: entry.time, data: entry.data, ttl: elapsed };
20
- attemptsStore[identifier] = entryID;
21
- if (elapsed <= 0) {
22
- del(identifier);
23
- return 0;
24
- }
25
- return elapsed;
26
- }
6
+ const attemptsStore = {};
7
+ let timeoutJob = null;
27
8
 
28
9
  /* set data and timeout */
29
- function set(identifier, data, time) {
10
+ Memory.set = function setService(identifier, data, time) {
30
11
  recordAttempt(identifier, data, time);
12
+ running();
31
13
  return "created";
32
- }
14
+ };
33
15
 
34
16
  /* get data by id */
35
- function get(identifier) {
17
+ Memory.get = function getService(identifier) {
36
18
  const now = Date.now();
37
19
  const entry = attemptsStore[identifier];
38
20
  if (!entry) return null;
39
21
 
40
22
  const timeout = entry.time - now;
41
- getRemainingTime(identifier);
23
+ ttlService(identifier);
42
24
  if (timeout <= 0) {
43
- del(identifier);
44
25
  return null;
45
26
  }
46
27
  return attemptsStore[identifier].data;
47
- }
28
+ };
48
29
 
49
30
  /* get all data */
50
- function multiple() {
31
+ Memory.multiple = function multipleService() {
32
+ for (const identifier in attemptsStore) {
33
+ ttlService(identifier);
34
+ }
51
35
  return Object.entries(attemptsStore).map(([id, entry]) => ({
52
36
  id,
53
37
  data: entry.data,
54
38
  }));
55
- }
56
-
57
- /* delete data by id */
58
- function del(identifier) {
59
- delete attemptsStore[identifier];
60
- return "deleted";
61
- }
39
+ };
62
40
 
63
41
  /* delete all data */
64
- function delall() {
42
+ Memory.delall = function delallService() {
65
43
  Object.keys(attemptsStore).forEach((key) => delete attemptsStore[key]);
66
44
  return "deleted";
67
- }
45
+ };
46
+
47
+ /* validate timeout */
48
+ Memory.ttl = ttlService;
68
49
 
50
+ /* delete data by id */
51
+ Memory.del = delService;
52
+
53
+ /**
54
+ * private util functions
55
+ */
69
56
  /* delete data has expire in 15 minutes. */
70
- setInterval(() => {
57
+ function running() {
58
+ const now = Date.now();
59
+ const elapsed = timeoutJob - now;
60
+ if (elapsed > 0) {
61
+ return;
62
+ }
71
63
  for (const identifier in attemptsStore) {
72
- getRemainingTime(identifier);
64
+ ttlService(identifier);
73
65
  }
74
- }, 900 * 1000);
66
+ const expiryTime = now + 900 * 1000;
67
+ timeoutJob = expiryTime;
68
+ }
75
69
 
76
- module.exports = {
77
- set,
78
- get,
79
- ttl: getRemainingTime,
80
- del,
81
- multiple,
82
- delall,
83
- };
70
+ function recordAttempt(identifier, data, timeoutSeconds) {
71
+ const now = Date.now();
72
+ const expiryTime = now + timeoutSeconds * 1000;
73
+ const elapsed = expiryTime - now;
74
+ const entry = { time: expiryTime, data, ttl: elapsed };
75
+ attemptsStore[identifier] = entry;
76
+ return entry;
77
+ }
78
+
79
+ function ttlService(identifier) {
80
+ const entry = attemptsStore[identifier];
81
+ if (!entry) return 0;
82
+ const now = Date.now();
83
+ const elapsed = entry.time - now;
84
+ const entryID = { time: entry.time, data: entry.data, ttl: elapsed };
85
+ attemptsStore[identifier] = entryID;
86
+ if (elapsed <= 0) {
87
+ delService(identifier);
88
+ return 0;
89
+ }
90
+ return elapsed;
91
+ }
92
+
93
+ function delService(identifier) {
94
+ delete attemptsStore[identifier];
95
+ return "deleted";
96
+ }
package/lib/worker.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * expose object
3
+ */
4
+ let Task = module.exports;
5
+ let tasks = [];
6
+ let isProcessing = false;
7
+ let taskId = 0;
8
+ let registeredFns = {};
9
+
10
+ /**
11
+ * Add a job into the queue (before the processor is defined)
12
+ */
13
+ Task.addTask = function (name = "temp", data = {}, retries = 1) {
14
+ taskId += 1;
15
+ retries = !retries ? 1 : retries > 5 ? 5 : retries;
16
+
17
+ const task = {
18
+ id: taskId,
19
+ name,
20
+ data,
21
+ attempts: 0,
22
+ maxAttempts: retries,
23
+ };
24
+
25
+ tasks.push(task);
26
+ processTasks();
27
+
28
+ return { id: task.id };
29
+ };
30
+
31
+ /**
32
+ * Register a processor for a task name
33
+ */
34
+ Task.runTask = function (name, taskFn) {
35
+ if (typeof taskFn !== "function") {
36
+ throw new Error("Task must be a function");
37
+ }
38
+ registeredFns[name] = taskFn;
39
+ processTasks();
40
+ };
41
+
42
+ /**
43
+ * private util functions
44
+ */
45
+ async function processTasks() {
46
+ if (isProcessing) return;
47
+ isProcessing = true;
48
+
49
+ while (tasks.length > 0) {
50
+ const task = tasks.shift();
51
+ const fn = registeredFns[task.name];
52
+
53
+ if (!fn) {
54
+ // processor not defined yet → put it back and stop
55
+ tasks.unshift(task);
56
+ break;
57
+ }
58
+
59
+ try {
60
+ task.attempts += 1;
61
+ await fn.call({ data: task.data, id: task.id, name: task.name });
62
+ } catch (err) {
63
+ if (task.attempts < task.maxAttempts) {
64
+ tasks.push(task);
65
+ }
66
+ }
67
+ }
68
+
69
+ isProcessing = false;
70
+ }
package/package.json CHANGED
@@ -1,12 +1,20 @@
1
1
  {
2
2
  "name": "memory-sri",
3
- "version": "1.0.3",
4
- "description": "A simple and customizable memory data utility for Node.js",
5
- "main": "index.js",
3
+ "version": "1.2.1",
4
+ "description": "A simple and customizable memory data per 1 loadbalance",
6
5
  "scripts": {
7
- "test": "echo \"No tests specified\" && exit 0",
6
+ "test": "npx jest ---coverage=false --detectOpenHandles --forceExit",
7
+ "exit": "echo \"No tests specified\" && exit 0",
8
8
  "dev": "node index.js"
9
9
  },
10
+ "author": "Santipap Eiamsamlee",
11
+ "license": "MIT",
12
+ "files": [
13
+ "README.md",
14
+ "index.js",
15
+ "index.d.ts",
16
+ "lib"
17
+ ],
10
18
  "keywords": [
11
19
  "temp",
12
20
  "memory",
@@ -16,6 +24,7 @@
16
24
  "utility",
17
25
  "integration"
18
26
  ],
19
- "author": "Santipap Eiamsamlee",
20
- "license": "MIT"
27
+ "main": "./index",
28
+ "types": "./index.d.ts",
29
+ "typings": "./index.d.ts"
21
30
  }