septor-store 0.0.6 → 1.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/README.md CHANGED
@@ -1,4 +1,5 @@
1
1
  # Vue 3 + TypeScript + Vite
2
+
2
3
  <p align="center">
3
4
  <img src="https://github.com/ssengedonazil/septor-store-testing/blob/POM/assets/septor-store.png?raw=true" alt="Septor Logo" width="180" />
4
5
  </p>
@@ -22,6 +23,7 @@ septor-store is a structured and scalable state management solution built on top
22
23
  | Post + Submit Support | Easily manage POST data and track responses |
23
24
  | Flexible Callbacks | Use custom callbacks on state update |
24
25
  | Loading & Error States | Built-in support for loading/errors |
26
+ | clean all the state against the store id
25
27
 
26
28
  - Automatic API Call Queue Management Prevents multiple simultaneous calls to the same endpoint by tracking ongoing requests.
27
29
  - Session Storage Caching Support Optionally caches API responses in sessionStorage for faster retrieval and offline resilience.
@@ -266,7 +268,44 @@ const handleSubmit = async () => {
266
268
  </script>
267
269
 
268
270
  ```
271
+
272
+ ### Usage **EXAMPLE 3** Remove all the data stored(cleare)🤭
273
+
274
+ ```
275
+ Note: StateClean this activates the opearation
276
+
277
+ const usePomStore = pomPinia('myCustomStoreId',null,{StateClean:true});
278
+ const pomStore = usePomStore();
279
+
280
+
281
+ const handleSubmit = async () => {
282
+ const config = {
283
+ StateStore: 'packageList',
284
+ reqs: {
285
+ url: '/api/packagelist', //call your endpoint
286
+ method: 'post',
287
+ data: user.value,
288
+ },
289
+ reload: true,
290
+ }
291
+
292
+ const res = await pomStore.stateGenaratorApi(config, (oldData) => {
293
+ console.log('Previous post result if any:', oldData)
294
+ })
295
+ result.value = res
296
+ }
297
+
298
+ pomStore.WipeStates(stateId) // remove just a paticular id (eg packageList)
299
+ pomStore.WipeStates() // remove all the states
300
+
301
+ ```
302
+
303
+ 🤝 Contributing and Feedback
304
+ We welcome all contributions and feedback to improve septor-store!
305
+ If you encounter any bugs, have suggestions, or want to contribute,
306
+ please open an issue or submit a pull request:
307
+ 👉 Report Issues or Suggestions : <https://github.com/ssengedonazil/septor-store-testing>
308
+
269
309
  If you find this package useful, consider supporting me:
270
310
 
271
311
  [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/ssengendonazil)
272
-
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "septor-store",
3
- "description": "septor-store is a structured and scalable state management solution built on top of Pinia for Vue 3. It embraces the Plain Old Module (POM) pattern to simplify how developers—junior or senior—write, organize, and scale their application state. Whether you're just starting out or architecting large Vue applications, this tool helps you keep your stores clean, predictable, and easy to indextain.",
3
+ "description": "A powerful, modular state management solution for Vue 3 applications, built on top of Pinia. Septor Store leverages the Plain Old Module (POM) pattern to provide dynamic store generation, intelligent API request handling, smart caching, and clean separation of concerns—making it ideal for scalable, maintainable, and high-performance frontend development.",
4
4
  "private": false,
5
5
  "license": "MIT",
6
- "version": "0.0.6",
6
+ "version": "1.0.0",
7
7
  "type": "module",
8
8
  "main": "dist/index.cjs",
9
9
  "module": "dist/index.js",
@@ -25,53 +25,49 @@
25
25
  "vue": "^3.5.13"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/axios": "^0.14.4",
28
+ "@types/axios": "^0.14.4",
29
29
  "tsup": "^8.4.0",
30
30
  "typescript": "~5.8.3"
31
31
  },
32
32
  "keywords": [
33
- "pinia",
34
33
  "vue",
34
+ "vue3",
35
+ "pinia",
36
+ "pinia store",
37
+ "vue pinia plugin",
35
38
  "state management",
36
- "store",
37
- "node",
38
- "Ajax",
39
- "promise",
40
- "vue",
41
- "vue3",
42
- "state",
43
- "pom",
44
- "pom-pattern",
45
- "vue-pinia",
46
- "vue-store",
47
- "pinia-store",
48
- "modular-state",
49
- "api-cache",
50
- "api-state-manager",
51
- "typescript",
52
- "vue-typescript",
53
- "pinia-plugin",
54
- "state-library",
39
+ "vue state management",
40
+ "api caching",
41
+ "vue ssr",
42
+ "vue spa",
43
+ "store plugin",
44
+ "modular state",
45
+ "dynamic store",
46
+ "state persistence",
55
47
  "frontend tools",
56
- "reactive-state",
57
- "session-storage",
58
- "dynamic-store",
59
- "paginated-api",
60
- "vue devtools",
61
- "session persistence",
48
+ "api queue",
49
+ "session storage",
50
+ "pom pattern",
51
+ "plain old module",
52
+ "vue typescript",
53
+ "typescript",
54
+ "reactive state",
55
+ "data fetching",
62
56
  "vuex alternative",
63
- "smart cache",
64
- "Septor Store",
65
- "api-queue",
66
- "septor-store-vue",
67
- "reload-control"
57
+ "state library",
58
+ "state sync",
59
+ "loading state",
60
+ "vue plugin",
61
+ "pinia plugin",
62
+ "septor store",
63
+ "septor-store-vue"
68
64
  ],
69
65
  "funding": [
70
- {
71
- "type": "ko-fi",
72
- "url": "https://ko-fi.com/ssengedonazil"
73
- }
74
- ],
66
+ {
67
+ "type": "ko-fi",
68
+ "url": "https://ko-fi.com/ssengedonazil"
69
+ }
70
+ ],
75
71
  "author": "Ssengendo Nazil",
76
72
  "repository": {
77
73
  "type": "git",
package/dist/index.cjs DELETED
@@ -1,309 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/index.js
30
- var index_exports = {};
31
- __export(index_exports, {
32
- generateParams: () => generateParams,
33
- getBearerToken: () => getBearerToken,
34
- pomPinia: () => createPomStore,
35
- setBearerToken: () => setBearerToken,
36
- useFetch: () => useFetch
37
- });
38
- module.exports = __toCommonJS(index_exports);
39
-
40
- // src/StoreManager/pomStateManagement.js
41
- var import_pinia = require("pinia");
42
-
43
- // src/utils/custom-axios.js
44
- var import_axios = __toESM(require("axios"), 1);
45
-
46
- // src/utils/abortHandler.js
47
- var AbortHandler = {
48
- abortController: new AbortController(),
49
- abortHttpRequests() {
50
- this.abortController.abort();
51
- this.abortController = new AbortController();
52
- custom_axios_default.defaults.signal = this.abortController.signal;
53
- }
54
- };
55
- var abortHandler_default = AbortHandler;
56
-
57
- // src/utils/custom-axios.js
58
- var import_meta = {};
59
- var baseURL = typeof import_meta !== "undefined" ? import_meta.env.VITE_BACKEND_URL ?? "" : "";
60
- var customAxios = import_axios.default.create({
61
- baseURL,
62
- signal: abortHandler_default.abortController.signal
63
- // Signal that is assiciated with any request to be made with this axios instance
64
- });
65
- var requestHandler = (request) => {
66
- const tokenData = getBearerToken();
67
- const token = (tokenData == null ? void 0 : tokenData.token) ?? null;
68
- const expiresIn = (tokenData == null ? void 0 : tokenData.expiresIn) ?? null;
69
- if (expiresIn) {
70
- const timestamp = (tokenData == null ? void 0 : tokenData.timestamp) ?? null;
71
- const now = Date.now();
72
- if (expiresIn && now - timestamp > expiresIn * 1e3) {
73
- console.warn("Token has expired.");
74
- localStorage.removeItem("logginToken");
75
- return null;
76
- }
77
- }
78
- if (token) {
79
- request.headers.Authorization = `Bearer ${token}`;
80
- }
81
- if (request.data instanceof FormData) {
82
- const formData = request.data;
83
- request.data = formData;
84
- } else if (request.data) {
85
- request.data = { ...request.data ?? {} };
86
- }
87
- return request;
88
- };
89
- customAxios.interceptors.response.use(
90
- (response) => response,
91
- // Resolve response as is
92
- (error) => {
93
- var _a;
94
- console.log("Error.....", error);
95
- if (((_a = error.response) == null ? void 0 : _a.status) === 401) {
96
- }
97
- return Promise.reject(error);
98
- }
99
- );
100
- customAxios.interceptors.request.use(
101
- requestHandler,
102
- (error) => Promise.reject(error)
103
- );
104
- var custom_axios_default = customAxios;
105
-
106
- // src/utils/useFetch.js
107
- var useFetch = async ({ url, method, data }) => {
108
- let _data = data ?? {};
109
- try {
110
- let response = null;
111
- const uniformMethod = method.toLowerCase();
112
- if (uniformMethod === "get") {
113
- const params = generateParams(_data ?? {});
114
- response = await custom_axios_default.get(`${url}${params}`);
115
- } else
116
- response = await custom_axios_default.post(url, _data);
117
- return (response == null ? void 0 : response.data) ?? { Empty: "Empty" };
118
- } catch (err2) {
119
- console.error(err2);
120
- return { success: false, error: err2 };
121
- }
122
- };
123
- var generateParams = (params = {}) => {
124
- try {
125
- let data = "?";
126
- for (let key in params) {
127
- if (Object.hasOwnProperty.call(params, key)) {
128
- if (params[key]) {
129
- if (Array.isArray(params[key])) {
130
- const elements = params[key];
131
- for (const ele of elements) {
132
- data += `${key}[]=${ele}&`;
133
- }
134
- } else {
135
- data += `${key}=${params[key]}&`;
136
- }
137
- }
138
- }
139
- }
140
- return data.slice(0, -1);
141
- } catch (error) {
142
- console.error(err);
143
- }
144
- };
145
- function setBearerToken(name = { token: null }) {
146
- if (typeof name !== "object" || name === null || Array.isArray(name))
147
- throw new TypeError("setBearerToken expects an object {token} with a 'token' property.");
148
- const tokenObj = { token: null, ...name, timestamp: Date.now() };
149
- localStorage.setItem("logginToken", JSON.stringify(tokenObj));
150
- }
151
- function getBearerToken() {
152
- const token = localStorage.getItem("logginToken");
153
- try {
154
- return token ? JSON.parse(token) : null;
155
- } catch (e) {
156
- console.error("Invalid token format in localStorage:", e);
157
- return null;
158
- }
159
- }
160
-
161
- // src/StoreManager/pomStateManagement.js
162
- function createPomStore(piniaStore = "7286204094", callBack = null) {
163
- const storeId = "POM" + piniaStore;
164
- const piniaData = (0, import_pinia.defineStore)(storeId, {
165
- state: () => {
166
- const StateObjectsContainer = {
167
- CheckQueriesInQue: {},
168
- StateValue: {},
169
- Loading: true,
170
- isThereAnyDataChangeInAform: false
171
- };
172
- return StateObjectsContainer;
173
- },
174
- getters: {
175
- stateItems: (state) => (TagetState) => {
176
- return state[TagetState] = state[TagetState];
177
- }
178
- },
179
- actions: {
180
- validateObjectLength(object) {
181
- if (Array.isArray(object)) {
182
- return object.length;
183
- } else if (typeof object == "object") {
184
- const lng = Object.keys(object);
185
- return lng.length;
186
- }
187
- return 0;
188
- },
189
- pageNumber(pageUrl) {
190
- const inputString = pageUrl;
191
- const regex = /\?(page)+=\d+/;
192
- const match = regex.exec(inputString);
193
- if (match) {
194
- const matchedPattern = match[0];
195
- const dataBack = matchedPattern.split("?page=").join().replace(/[^\d]/, "");
196
- return dataBack;
197
- } else return "1";
198
- },
199
- sleep(timer) {
200
- return new Promise((r) => setTimeout(r, timer));
201
- },
202
- async CallApiData(StateStore, callApi, dataParams, pagnated, mStore = {}) {
203
- if (!this.CheckQueriesInQue[callApi]) {
204
- this.CheckQueriesInQue[callApi] = callApi;
205
- let [res] = await Promise.all([
206
- useFetch(dataParams)
207
- ]);
208
- if (res) {
209
- this[StateStore] = res;
210
- if (mStore == null ? void 0 : mStore.mUse) {
211
- const checkType = typeof res === "object" ? JSON.stringify(res) : res;
212
- sessionStorage.setItem(StateStore, JSON.stringify(checkType));
213
- }
214
- delete this.CheckQueriesInQue[callApi];
215
- } else {
216
- delete this.CheckQueriesInQue[callApi];
217
- console.error(res);
218
- }
219
- this.Loading = false;
220
- return res;
221
- }
222
- this.Loading = false;
223
- return this[StateStore] ?? [];
224
- },
225
- async parseData(dataResponseName = "xxx", mStore = { mUse: false, reset: false }) {
226
- try {
227
- if (mStore == null ? void 0 : mStore.reset) {
228
- sessionStorage.removeItem(dataResponseName);
229
- }
230
- if (mStore == null ? void 0 : mStore.mUse) {
231
- const thisData = JSON.parse(
232
- JSON.parse(sessionStorage.getItem(dataResponseName) || {})
233
- );
234
- return thisData;
235
- }
236
- } catch (error) {
237
- }
238
- return this[dataResponseName];
239
- },
240
- async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0 } }, fasterDataCollection = null) {
241
- this.Loading = true;
242
- const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
243
- const callApi = JSON.stringify(reqs);
244
- const StateVariable = await this.parseData(StateStore, mStore);
245
- this[StateStore] = StateVariable ?? [];
246
- if (this.StateValue[StateStore]) {
247
- this.StateValue[StateStore] = false;
248
- this[StateStore] = false;
249
- }
250
- if (this.CheckQueriesInQue[callApi]) {
251
- console.warn(`************************************* dont call this api again ${reqs["url"]} \u{1F6E9}\uFE0F *************************************`, reqs);
252
- return;
253
- }
254
- try {
255
- const counters = this.validateObjectLength(StateVariable);
256
- if (typeof fasterDataCollection == "function")
257
- fasterDataCollection(StateVariable);
258
- if (counters > 0) {
259
- if (reload) {
260
- const delay = await this.sleep(1e3 * time);
261
- return await this.CallApiData(
262
- StateStore,
263
- callApi,
264
- reqs,
265
- pagnated,
266
- mStore
267
- );
268
- }
269
- this.Loading = false;
270
- return this[StateStore];
271
- } else {
272
- this.Loading = true;
273
- }
274
- return await this.CallApiData(
275
- StateStore,
276
- callApi,
277
- reqs,
278
- pagnated,
279
- mStore
280
- );
281
- } catch (error) {
282
- if (this.CheckQueriesInQue[callApi])
283
- delete this.CheckQueriesInQue[callApi];
284
- }
285
- },
286
- Creator() {
287
- if (typeof callBack === "function") {
288
- return callBack(this);
289
- }
290
- },
291
- DriveManual() {
292
- return function() {
293
- return this;
294
- };
295
- },
296
- pagenatedData() {
297
- }
298
- }
299
- });
300
- return piniaData();
301
- }
302
- // Annotate the CommonJS export names for ESM import in node:
303
- 0 && (module.exports = {
304
- generateParams,
305
- getBearerToken,
306
- pomPinia,
307
- setBearerToken,
308
- useFetch
309
- });
package/dist/index.d.cts DELETED
@@ -1,306 +0,0 @@
1
- import { defineStore } from 'pinia';
2
- import axios from 'axios';
3
-
4
- const AbortHandler = {
5
- abortController: new AbortController()};
6
-
7
- const baseURL = typeof import.meta !== 'undefined' ? (import.meta.env.VITE_BACKEND_URL ??""): "";
8
-
9
- const customAxios = axios.create({
10
- baseURL: baseURL,
11
- signal: AbortHandler.abortController.signal, // Signal that is assiciated with any request to be made with this axios instance
12
- });
13
-
14
- // Request Interceptor
15
- const requestHandler = (request) => {
16
- const tokenData = getBearerToken();
17
- const token = tokenData?.token ?? null; // Always retrieve the latest token
18
- const expiresIn = tokenData?.expiresIn ?? null;
19
-
20
- if (expiresIn) {
21
- const timestamp = tokenData?.timestamp ?? null;
22
- const now = Date.now();
23
- if (expiresIn && (now - timestamp) > (expiresIn * 1000)) {
24
- console.warn("Token has expired.");
25
- localStorage.removeItem("logginToken");
26
- return null;
27
- }
28
- }
29
-
30
- if (token) {
31
- request.headers.Authorization = `Bearer ${token}`;
32
- }
33
-
34
- // Handle FormData explicitly if needed
35
- if (request.data instanceof FormData) {
36
- const formData = request.data;
37
- request.data = formData;
38
- } else if (request.data) {
39
- request.data = { ...(request.data ?? {}) };
40
- }
41
-
42
- return request;
43
- };
44
-
45
- // Response Interceptor
46
- customAxios.interceptors.response.use(
47
- (response) => response, // Resolve response as is
48
- (error) => {
49
- console.log("Error.....", error);
50
- if (error.response?.status === 401) ;
51
- return Promise.reject(error); // Reject the error for further handling
52
- }
53
- );
54
-
55
- // Attach Request Interceptor
56
- customAxios.interceptors.request.use(requestHandler, (error) =>
57
- Promise.reject(error)
58
- );
59
-
60
- const useFetch = async ({ url, method, data }) => {
61
- let _data = data ?? {};
62
- try {
63
- let response=null;
64
- const uniformMethod = method.toLowerCase();
65
- if (uniformMethod === 'get') {
66
- const params = generateParams(_data ?? {});
67
- response = await customAxios.get(`${url}${params}`);
68
- } else
69
- response = await customAxios.post(url, _data);
70
-
71
- return response?.data ?? { Empty: 'Empty' };
72
- } catch (err) {
73
- console.error(err);
74
- return { success: false, error: err };
75
- }
76
- };
77
-
78
- const generateParams = (params={}) => {
79
- try {
80
-
81
- let data = "?";
82
- for (let key in params) {
83
- if (Object.hasOwnProperty.call(params, key)) {
84
- if (params[key]) {
85
- if (Array.isArray(params[key])) {
86
- const elements = params[key] ;
87
- for (const ele of elements) {
88
- data += `${key}[]=${ele}&`;
89
- }
90
- } else {
91
- data += `${key}=${params[key]}&`;
92
- }
93
- }
94
- }
95
- }
96
- return data.slice(0, -1);
97
- } catch (error) {
98
- console.error(err);
99
-
100
- }
101
- };
102
-
103
- function setBearerToken(name = { token: null }) {
104
- if (typeof name !== "object" || name === null || Array.isArray(name))
105
- throw new TypeError("setBearerToken expects an object {token} with a 'token' property.");
106
-
107
- const tokenObj = { token: null, ...name,timestamp: Date.now() };
108
- localStorage.setItem("logginToken", JSON.stringify(tokenObj));
109
- }
110
-
111
- function getBearerToken() {
112
- const token = localStorage.getItem('logginToken');
113
- try {
114
- return token ? JSON.parse(token) : null;
115
- } catch (e) {
116
- console.error('Invalid token format in localStorage:', e);
117
- return null;
118
- }
119
- }
120
-
121
- function createPomStore( piniaStore = "7286204094", callBack=null) {
122
- const storeId = "POM" + piniaStore;
123
- const piniaData = defineStore(storeId, {
124
- state: () => {
125
- const StateObjectsContainer = {
126
- CheckQueriesInQue: {},
127
- StateValue: {},
128
- Loading: true,
129
- isThereAnyDataChangeInAform: false,
130
- };
131
-
132
- return StateObjectsContainer;
133
- },
134
-
135
- getters: {
136
- stateItems: (state) => (TagetState) => {
137
- /**
138
- make data basing on state TagetState this acts as a clusure in ()() read about it
139
- store.stateItems(key1) usage to ge the ge
140
- *
141
- */
142
- return (state[TagetState] = state[TagetState]);
143
- },
144
-
145
- },
146
- actions: {
147
- validateObjectLength(object) {
148
- if (Array.isArray(object)) {
149
- return object.length;
150
- } else if (typeof object == "object") {
151
- const lng = Object.keys(object);
152
- return lng.length;
153
- }
154
- return 0;
155
- },
156
- pageNumber(pageUrl) {
157
- const inputString = pageUrl; //'?page=124234232&&';
158
- const regex = /\?(page)+=\d+/;
159
- const match = regex.exec(inputString);
160
-
161
- if (match) {
162
- // /according to the patern ' i expect 1 value /
163
- const matchedPattern = match[0];
164
- const dataBack = matchedPattern
165
- .split("?page=")
166
- .join()
167
- .replace(/[^\d]/, "");
168
-
169
- return dataBack;
170
- } else return "1";
171
- },
172
- sleep(timer) {
173
- return new Promise((r) => setTimeout(r, timer));
174
- },
175
-
176
- async CallApiData(
177
- StateStore,
178
- callApi,
179
- dataParams,
180
- pagnated ,
181
- mStore={}
182
- ) {
183
- if (!this.CheckQueriesInQue[callApi]) {
184
- this.CheckQueriesInQue[callApi] = callApi;
185
- let [res] = await Promise.all([
186
- useFetch (dataParams),
187
- ]);
188
-
189
- if (res) {
190
- this[StateStore] = res;
191
- if (mStore?.mUse) {
192
- const checkType =typeof res === "object" ? JSON.stringify(res) : res;
193
- sessionStorage.setItem(StateStore, JSON.stringify(checkType));
194
- }
195
-
196
- delete this.CheckQueriesInQue[callApi];
197
- } else {
198
- delete this.CheckQueriesInQue[callApi];
199
- console.error(res);
200
- }
201
- this.Loading = false;
202
- return res;
203
- }
204
- this.Loading = false;
205
- return this[StateStore] ?? [];
206
- },
207
- async parseData(
208
- dataResponseName = "xxx",
209
- mStore = { mUse: false, reset: false }
210
- ) {
211
- try {
212
- if (mStore?.reset) {
213
- sessionStorage.removeItem(dataResponseName);
214
- }
215
-
216
- if (mStore?.mUse) {
217
- const thisData = JSON.parse(
218
- JSON.parse(sessionStorage.getItem(dataResponseName) || {})
219
- );
220
-
221
- return thisData;
222
- }
223
- } catch (error) {}
224
-
225
- return this[dataResponseName];
226
- },
227
- async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0 },},fasterDataCollection=null) {
228
- this.Loading = true;
229
- const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
230
- const callApi = JSON.stringify(reqs);
231
- const StateVariable = await this.parseData(StateStore, mStore);
232
- this[StateStore] = StateVariable ?? [];
233
-
234
- if (this.StateValue[StateStore]) {
235
- /**
236
- * dynamically lets create the state store
237
- **/
238
- this.StateValue[StateStore] = false;
239
- this[StateStore] = false;
240
- // this[StateStore] =null ;
241
- }
242
-
243
- if (this.CheckQueriesInQue[callApi]) {
244
- console.warn(`************************************* dont call this api again ${reqs["url"]} 🛩️ *************************************`,reqs);
245
- return;
246
- }
247
- try {
248
- const counters = this.validateObjectLength(StateVariable);
249
- if (typeof fasterDataCollection == "function")
250
- fasterDataCollection(StateVariable);
251
-
252
- if (counters > 0) {
253
- if (reload) {
254
- const delay = await this.sleep(1000 * time);
255
- return await this.CallApiData(
256
- StateStore,
257
- callApi,
258
- reqs,
259
- pagnated,
260
- mStore
261
- );
262
- }
263
-
264
- this.Loading = false;
265
- return this[StateStore];
266
- } else {
267
- this.Loading = true;
268
- }
269
-
270
- return await this.CallApiData(
271
- StateStore,
272
- callApi,
273
- reqs,
274
- pagnated,
275
- mStore
276
- );
277
- } catch (error) {
278
- // console.error(error);
279
- if (this.CheckQueriesInQue[callApi])
280
- delete this.CheckQueriesInQue[callApi];
281
- }
282
- },
283
- Creator() {
284
- /**
285
- *
286
- * this will retun a call back wth the full object
287
- * **/
288
- if (typeof callBack === "function") {
289
- return callBack(this);
290
- }
291
- },
292
- DriveManual() {
293
- return function () {
294
- return this;
295
- };
296
- },
297
- pagenatedData() {},
298
- },
299
- });
300
-
301
- return piniaData();
302
- }
303
-
304
- // module.e = createPomStore
305
-
306
- export { generateParams, getBearerToken, createPomStore as pomPinia, setBearerToken, useFetch };
package/dist/index.d.ts DELETED
@@ -1,306 +0,0 @@
1
- import { defineStore } from 'pinia';
2
- import axios from 'axios';
3
-
4
- const AbortHandler = {
5
- abortController: new AbortController()};
6
-
7
- const baseURL = typeof import.meta !== 'undefined' ? (import.meta.env.VITE_BACKEND_URL ??""): "";
8
-
9
- const customAxios = axios.create({
10
- baseURL: baseURL,
11
- signal: AbortHandler.abortController.signal, // Signal that is assiciated with any request to be made with this axios instance
12
- });
13
-
14
- // Request Interceptor
15
- const requestHandler = (request) => {
16
- const tokenData = getBearerToken();
17
- const token = tokenData?.token ?? null; // Always retrieve the latest token
18
- const expiresIn = tokenData?.expiresIn ?? null;
19
-
20
- if (expiresIn) {
21
- const timestamp = tokenData?.timestamp ?? null;
22
- const now = Date.now();
23
- if (expiresIn && (now - timestamp) > (expiresIn * 1000)) {
24
- console.warn("Token has expired.");
25
- localStorage.removeItem("logginToken");
26
- return null;
27
- }
28
- }
29
-
30
- if (token) {
31
- request.headers.Authorization = `Bearer ${token}`;
32
- }
33
-
34
- // Handle FormData explicitly if needed
35
- if (request.data instanceof FormData) {
36
- const formData = request.data;
37
- request.data = formData;
38
- } else if (request.data) {
39
- request.data = { ...(request.data ?? {}) };
40
- }
41
-
42
- return request;
43
- };
44
-
45
- // Response Interceptor
46
- customAxios.interceptors.response.use(
47
- (response) => response, // Resolve response as is
48
- (error) => {
49
- console.log("Error.....", error);
50
- if (error.response?.status === 401) ;
51
- return Promise.reject(error); // Reject the error for further handling
52
- }
53
- );
54
-
55
- // Attach Request Interceptor
56
- customAxios.interceptors.request.use(requestHandler, (error) =>
57
- Promise.reject(error)
58
- );
59
-
60
- const useFetch = async ({ url, method, data }) => {
61
- let _data = data ?? {};
62
- try {
63
- let response=null;
64
- const uniformMethod = method.toLowerCase();
65
- if (uniformMethod === 'get') {
66
- const params = generateParams(_data ?? {});
67
- response = await customAxios.get(`${url}${params}`);
68
- } else
69
- response = await customAxios.post(url, _data);
70
-
71
- return response?.data ?? { Empty: 'Empty' };
72
- } catch (err) {
73
- console.error(err);
74
- return { success: false, error: err };
75
- }
76
- };
77
-
78
- const generateParams = (params={}) => {
79
- try {
80
-
81
- let data = "?";
82
- for (let key in params) {
83
- if (Object.hasOwnProperty.call(params, key)) {
84
- if (params[key]) {
85
- if (Array.isArray(params[key])) {
86
- const elements = params[key] ;
87
- for (const ele of elements) {
88
- data += `${key}[]=${ele}&`;
89
- }
90
- } else {
91
- data += `${key}=${params[key]}&`;
92
- }
93
- }
94
- }
95
- }
96
- return data.slice(0, -1);
97
- } catch (error) {
98
- console.error(err);
99
-
100
- }
101
- };
102
-
103
- function setBearerToken(name = { token: null }) {
104
- if (typeof name !== "object" || name === null || Array.isArray(name))
105
- throw new TypeError("setBearerToken expects an object {token} with a 'token' property.");
106
-
107
- const tokenObj = { token: null, ...name,timestamp: Date.now() };
108
- localStorage.setItem("logginToken", JSON.stringify(tokenObj));
109
- }
110
-
111
- function getBearerToken() {
112
- const token = localStorage.getItem('logginToken');
113
- try {
114
- return token ? JSON.parse(token) : null;
115
- } catch (e) {
116
- console.error('Invalid token format in localStorage:', e);
117
- return null;
118
- }
119
- }
120
-
121
- function createPomStore( piniaStore = "7286204094", callBack=null) {
122
- const storeId = "POM" + piniaStore;
123
- const piniaData = defineStore(storeId, {
124
- state: () => {
125
- const StateObjectsContainer = {
126
- CheckQueriesInQue: {},
127
- StateValue: {},
128
- Loading: true,
129
- isThereAnyDataChangeInAform: false,
130
- };
131
-
132
- return StateObjectsContainer;
133
- },
134
-
135
- getters: {
136
- stateItems: (state) => (TagetState) => {
137
- /**
138
- make data basing on state TagetState this acts as a clusure in ()() read about it
139
- store.stateItems(key1) usage to ge the ge
140
- *
141
- */
142
- return (state[TagetState] = state[TagetState]);
143
- },
144
-
145
- },
146
- actions: {
147
- validateObjectLength(object) {
148
- if (Array.isArray(object)) {
149
- return object.length;
150
- } else if (typeof object == "object") {
151
- const lng = Object.keys(object);
152
- return lng.length;
153
- }
154
- return 0;
155
- },
156
- pageNumber(pageUrl) {
157
- const inputString = pageUrl; //'?page=124234232&&';
158
- const regex = /\?(page)+=\d+/;
159
- const match = regex.exec(inputString);
160
-
161
- if (match) {
162
- // /according to the patern ' i expect 1 value /
163
- const matchedPattern = match[0];
164
- const dataBack = matchedPattern
165
- .split("?page=")
166
- .join()
167
- .replace(/[^\d]/, "");
168
-
169
- return dataBack;
170
- } else return "1";
171
- },
172
- sleep(timer) {
173
- return new Promise((r) => setTimeout(r, timer));
174
- },
175
-
176
- async CallApiData(
177
- StateStore,
178
- callApi,
179
- dataParams,
180
- pagnated ,
181
- mStore={}
182
- ) {
183
- if (!this.CheckQueriesInQue[callApi]) {
184
- this.CheckQueriesInQue[callApi] = callApi;
185
- let [res] = await Promise.all([
186
- useFetch (dataParams),
187
- ]);
188
-
189
- if (res) {
190
- this[StateStore] = res;
191
- if (mStore?.mUse) {
192
- const checkType =typeof res === "object" ? JSON.stringify(res) : res;
193
- sessionStorage.setItem(StateStore, JSON.stringify(checkType));
194
- }
195
-
196
- delete this.CheckQueriesInQue[callApi];
197
- } else {
198
- delete this.CheckQueriesInQue[callApi];
199
- console.error(res);
200
- }
201
- this.Loading = false;
202
- return res;
203
- }
204
- this.Loading = false;
205
- return this[StateStore] ?? [];
206
- },
207
- async parseData(
208
- dataResponseName = "xxx",
209
- mStore = { mUse: false, reset: false }
210
- ) {
211
- try {
212
- if (mStore?.reset) {
213
- sessionStorage.removeItem(dataResponseName);
214
- }
215
-
216
- if (mStore?.mUse) {
217
- const thisData = JSON.parse(
218
- JSON.parse(sessionStorage.getItem(dataResponseName) || {})
219
- );
220
-
221
- return thisData;
222
- }
223
- } catch (error) {}
224
-
225
- return this[dataResponseName];
226
- },
227
- async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0 },},fasterDataCollection=null) {
228
- this.Loading = true;
229
- const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
230
- const callApi = JSON.stringify(reqs);
231
- const StateVariable = await this.parseData(StateStore, mStore);
232
- this[StateStore] = StateVariable ?? [];
233
-
234
- if (this.StateValue[StateStore]) {
235
- /**
236
- * dynamically lets create the state store
237
- **/
238
- this.StateValue[StateStore] = false;
239
- this[StateStore] = false;
240
- // this[StateStore] =null ;
241
- }
242
-
243
- if (this.CheckQueriesInQue[callApi]) {
244
- console.warn(`************************************* dont call this api again ${reqs["url"]} 🛩️ *************************************`,reqs);
245
- return;
246
- }
247
- try {
248
- const counters = this.validateObjectLength(StateVariable);
249
- if (typeof fasterDataCollection == "function")
250
- fasterDataCollection(StateVariable);
251
-
252
- if (counters > 0) {
253
- if (reload) {
254
- const delay = await this.sleep(1000 * time);
255
- return await this.CallApiData(
256
- StateStore,
257
- callApi,
258
- reqs,
259
- pagnated,
260
- mStore
261
- );
262
- }
263
-
264
- this.Loading = false;
265
- return this[StateStore];
266
- } else {
267
- this.Loading = true;
268
- }
269
-
270
- return await this.CallApiData(
271
- StateStore,
272
- callApi,
273
- reqs,
274
- pagnated,
275
- mStore
276
- );
277
- } catch (error) {
278
- // console.error(error);
279
- if (this.CheckQueriesInQue[callApi])
280
- delete this.CheckQueriesInQue[callApi];
281
- }
282
- },
283
- Creator() {
284
- /**
285
- *
286
- * this will retun a call back wth the full object
287
- * **/
288
- if (typeof callBack === "function") {
289
- return callBack(this);
290
- }
291
- },
292
- DriveManual() {
293
- return function () {
294
- return this;
295
- };
296
- },
297
- pagenatedData() {},
298
- },
299
- });
300
-
301
- return piniaData();
302
- }
303
-
304
- // module.e = createPomStore
305
-
306
- export { generateParams, getBearerToken, createPomStore as pomPinia, setBearerToken, useFetch };
package/dist/index.js DELETED
@@ -1,268 +0,0 @@
1
- // src/StoreManager/pomStateManagement.js
2
- import { defineStore } from "pinia";
3
-
4
- // src/utils/custom-axios.js
5
- import axios from "axios";
6
-
7
- // src/utils/abortHandler.js
8
- var AbortHandler = {
9
- abortController: new AbortController(),
10
- abortHttpRequests() {
11
- this.abortController.abort();
12
- this.abortController = new AbortController();
13
- custom_axios_default.defaults.signal = this.abortController.signal;
14
- }
15
- };
16
- var abortHandler_default = AbortHandler;
17
-
18
- // src/utils/custom-axios.js
19
- var baseURL = typeof import.meta !== "undefined" ? import.meta.env.VITE_BACKEND_URL ?? "" : "";
20
- var customAxios = axios.create({
21
- baseURL,
22
- signal: abortHandler_default.abortController.signal
23
- // Signal that is assiciated with any request to be made with this axios instance
24
- });
25
- var requestHandler = (request) => {
26
- const tokenData = getBearerToken();
27
- const token = (tokenData == null ? void 0 : tokenData.token) ?? null;
28
- const expiresIn = (tokenData == null ? void 0 : tokenData.expiresIn) ?? null;
29
- if (expiresIn) {
30
- const timestamp = (tokenData == null ? void 0 : tokenData.timestamp) ?? null;
31
- const now = Date.now();
32
- if (expiresIn && now - timestamp > expiresIn * 1e3) {
33
- console.warn("Token has expired.");
34
- localStorage.removeItem("logginToken");
35
- return null;
36
- }
37
- }
38
- if (token) {
39
- request.headers.Authorization = `Bearer ${token}`;
40
- }
41
- if (request.data instanceof FormData) {
42
- const formData = request.data;
43
- request.data = formData;
44
- } else if (request.data) {
45
- request.data = { ...request.data ?? {} };
46
- }
47
- return request;
48
- };
49
- customAxios.interceptors.response.use(
50
- (response) => response,
51
- // Resolve response as is
52
- (error) => {
53
- var _a;
54
- console.log("Error.....", error);
55
- if (((_a = error.response) == null ? void 0 : _a.status) === 401) {
56
- }
57
- return Promise.reject(error);
58
- }
59
- );
60
- customAxios.interceptors.request.use(
61
- requestHandler,
62
- (error) => Promise.reject(error)
63
- );
64
- var custom_axios_default = customAxios;
65
-
66
- // src/utils/useFetch.js
67
- var useFetch = async ({ url, method, data }) => {
68
- let _data = data ?? {};
69
- try {
70
- let response = null;
71
- const uniformMethod = method.toLowerCase();
72
- if (uniformMethod === "get") {
73
- const params = generateParams(_data ?? {});
74
- response = await custom_axios_default.get(`${url}${params}`);
75
- } else
76
- response = await custom_axios_default.post(url, _data);
77
- return (response == null ? void 0 : response.data) ?? { Empty: "Empty" };
78
- } catch (err2) {
79
- console.error(err2);
80
- return { success: false, error: err2 };
81
- }
82
- };
83
- var generateParams = (params = {}) => {
84
- try {
85
- let data = "?";
86
- for (let key in params) {
87
- if (Object.hasOwnProperty.call(params, key)) {
88
- if (params[key]) {
89
- if (Array.isArray(params[key])) {
90
- const elements = params[key];
91
- for (const ele of elements) {
92
- data += `${key}[]=${ele}&`;
93
- }
94
- } else {
95
- data += `${key}=${params[key]}&`;
96
- }
97
- }
98
- }
99
- }
100
- return data.slice(0, -1);
101
- } catch (error) {
102
- console.error(err);
103
- }
104
- };
105
- function setBearerToken(name = { token: null }) {
106
- if (typeof name !== "object" || name === null || Array.isArray(name))
107
- throw new TypeError("setBearerToken expects an object {token} with a 'token' property.");
108
- const tokenObj = { token: null, ...name, timestamp: Date.now() };
109
- localStorage.setItem("logginToken", JSON.stringify(tokenObj));
110
- }
111
- function getBearerToken() {
112
- const token = localStorage.getItem("logginToken");
113
- try {
114
- return token ? JSON.parse(token) : null;
115
- } catch (e) {
116
- console.error("Invalid token format in localStorage:", e);
117
- return null;
118
- }
119
- }
120
-
121
- // src/StoreManager/pomStateManagement.js
122
- function createPomStore(piniaStore = "7286204094", callBack = null) {
123
- const storeId = "POM" + piniaStore;
124
- const piniaData = defineStore(storeId, {
125
- state: () => {
126
- const StateObjectsContainer = {
127
- CheckQueriesInQue: {},
128
- StateValue: {},
129
- Loading: true,
130
- isThereAnyDataChangeInAform: false
131
- };
132
- return StateObjectsContainer;
133
- },
134
- getters: {
135
- stateItems: (state) => (TagetState) => {
136
- return state[TagetState] = state[TagetState];
137
- }
138
- },
139
- actions: {
140
- validateObjectLength(object) {
141
- if (Array.isArray(object)) {
142
- return object.length;
143
- } else if (typeof object == "object") {
144
- const lng = Object.keys(object);
145
- return lng.length;
146
- }
147
- return 0;
148
- },
149
- pageNumber(pageUrl) {
150
- const inputString = pageUrl;
151
- const regex = /\?(page)+=\d+/;
152
- const match = regex.exec(inputString);
153
- if (match) {
154
- const matchedPattern = match[0];
155
- const dataBack = matchedPattern.split("?page=").join().replace(/[^\d]/, "");
156
- return dataBack;
157
- } else return "1";
158
- },
159
- sleep(timer) {
160
- return new Promise((r) => setTimeout(r, timer));
161
- },
162
- async CallApiData(StateStore, callApi, dataParams, pagnated, mStore = {}) {
163
- if (!this.CheckQueriesInQue[callApi]) {
164
- this.CheckQueriesInQue[callApi] = callApi;
165
- let [res] = await Promise.all([
166
- useFetch(dataParams)
167
- ]);
168
- if (res) {
169
- this[StateStore] = res;
170
- if (mStore == null ? void 0 : mStore.mUse) {
171
- const checkType = typeof res === "object" ? JSON.stringify(res) : res;
172
- sessionStorage.setItem(StateStore, JSON.stringify(checkType));
173
- }
174
- delete this.CheckQueriesInQue[callApi];
175
- } else {
176
- delete this.CheckQueriesInQue[callApi];
177
- console.error(res);
178
- }
179
- this.Loading = false;
180
- return res;
181
- }
182
- this.Loading = false;
183
- return this[StateStore] ?? [];
184
- },
185
- async parseData(dataResponseName = "xxx", mStore = { mUse: false, reset: false }) {
186
- try {
187
- if (mStore == null ? void 0 : mStore.reset) {
188
- sessionStorage.removeItem(dataResponseName);
189
- }
190
- if (mStore == null ? void 0 : mStore.mUse) {
191
- const thisData = JSON.parse(
192
- JSON.parse(sessionStorage.getItem(dataResponseName) || {})
193
- );
194
- return thisData;
195
- }
196
- } catch (error) {
197
- }
198
- return this[dataResponseName];
199
- },
200
- async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0 } }, fasterDataCollection = null) {
201
- this.Loading = true;
202
- const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
203
- const callApi = JSON.stringify(reqs);
204
- const StateVariable = await this.parseData(StateStore, mStore);
205
- this[StateStore] = StateVariable ?? [];
206
- if (this.StateValue[StateStore]) {
207
- this.StateValue[StateStore] = false;
208
- this[StateStore] = false;
209
- }
210
- if (this.CheckQueriesInQue[callApi]) {
211
- console.warn(`************************************* dont call this api again ${reqs["url"]} \u{1F6E9}\uFE0F *************************************`, reqs);
212
- return;
213
- }
214
- try {
215
- const counters = this.validateObjectLength(StateVariable);
216
- if (typeof fasterDataCollection == "function")
217
- fasterDataCollection(StateVariable);
218
- if (counters > 0) {
219
- if (reload) {
220
- const delay = await this.sleep(1e3 * time);
221
- return await this.CallApiData(
222
- StateStore,
223
- callApi,
224
- reqs,
225
- pagnated,
226
- mStore
227
- );
228
- }
229
- this.Loading = false;
230
- return this[StateStore];
231
- } else {
232
- this.Loading = true;
233
- }
234
- return await this.CallApiData(
235
- StateStore,
236
- callApi,
237
- reqs,
238
- pagnated,
239
- mStore
240
- );
241
- } catch (error) {
242
- if (this.CheckQueriesInQue[callApi])
243
- delete this.CheckQueriesInQue[callApi];
244
- }
245
- },
246
- Creator() {
247
- if (typeof callBack === "function") {
248
- return callBack(this);
249
- }
250
- },
251
- DriveManual() {
252
- return function() {
253
- return this;
254
- };
255
- },
256
- pagenatedData() {
257
- }
258
- }
259
- });
260
- return piniaData();
261
- }
262
- export {
263
- generateParams,
264
- getBearerToken,
265
- createPomStore as pomPinia,
266
- setBearerToken,
267
- useFetch
268
- };