septor-store 1.0.0 → 1.0.2

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
@@ -118,8 +118,8 @@ app.use(pinia);
118
118
  // functions.ts
119
119
  import { pomPinia,setBearerToken,getBearerToken } from "septor-store"
120
120
 
121
- const usePomStore = pomPinia('myCustomStoreId')|| pomPinia();
122
- const pomStore = usePomStore();
121
+ const pomStore = pomPinia('myCustomStoreId')|| pomPinia();
122
+
123
123
  // Example: Call API and store data
124
124
  const fetchData = async () => {
125
125
  const data = await pomStore.stateGenaratorApi({
package/dist/index.cjs ADDED
@@ -0,0 +1,326 @@
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
+ request.headers = { ...(request == null ? void 0 : request.headers) ?? {} };
79
+ if (token)
80
+ request.headers.Authorization = `Bearer ${token}`;
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, ds = { StateClean: 0 }) {
163
+ const storeId = "POM" + piniaStore;
164
+ const StateNameUsedSoferList = "septor-store-collection";
165
+ ;
166
+ const piniaData = (0, import_pinia.defineStore)(storeId, {
167
+ state: () => {
168
+ const StateObjectsContainer = {
169
+ CheckQueriesInQue: {},
170
+ StateValue: {},
171
+ Loading: true,
172
+ isThereAnyDataChangeInAform: false
173
+ };
174
+ return StateObjectsContainer;
175
+ },
176
+ getters: {
177
+ stateItems: (state) => (TagetState) => {
178
+ return state[TagetState] = state[TagetState];
179
+ }
180
+ },
181
+ actions: {
182
+ validateObjectLength(object) {
183
+ if (Array.isArray(object)) {
184
+ return object.length;
185
+ } else if (typeof object == "object") {
186
+ const lng = Object.keys(object);
187
+ return lng.length;
188
+ }
189
+ return 0;
190
+ },
191
+ pageNumber(pageUrl) {
192
+ const inputString = pageUrl;
193
+ const regex = /\?(page)+=\d+/;
194
+ const match = regex.exec(inputString);
195
+ if (match) {
196
+ const matchedPattern = match[0];
197
+ const dataBack = matchedPattern.split("?page=").join().replace(/[^\d]/, "");
198
+ return dataBack;
199
+ } else return "1";
200
+ },
201
+ sleep(timer) {
202
+ return new Promise((r) => setTimeout(r, timer));
203
+ },
204
+ async CallApiData(StateStore, callApi, dataParams, pagnated, mStore = {}) {
205
+ if (!this.CheckQueriesInQue[callApi]) {
206
+ this.CheckQueriesInQue[callApi] = callApi;
207
+ let [res] = await Promise.all([
208
+ useFetch(dataParams)
209
+ ]);
210
+ if (res) {
211
+ this[StateStore] = res;
212
+ if (mStore == null ? void 0 : mStore.mUse) {
213
+ const checkType = typeof res === "object" ? JSON.stringify(res) : res;
214
+ sessionStorage.setItem(StateStore, JSON.stringify(checkType));
215
+ }
216
+ delete this.CheckQueriesInQue[callApi];
217
+ } else {
218
+ delete this.CheckQueriesInQue[callApi];
219
+ console.error(res);
220
+ }
221
+ this.Loading = false;
222
+ return res;
223
+ }
224
+ this.Loading = false;
225
+ return this[StateStore] ?? [];
226
+ },
227
+ async parseData(dataResponseName = "xxx", mStore = { mUse: false, reset: false }) {
228
+ try {
229
+ if (mStore == null ? void 0 : mStore.reset) {
230
+ sessionStorage.removeItem(dataResponseName);
231
+ }
232
+ if (mStore == null ? void 0 : mStore.mUse) {
233
+ const thisData = JSON.parse(JSON.parse(sessionStorage.getItem(dataResponseName) || {}));
234
+ return thisData;
235
+ }
236
+ } catch (error) {
237
+ }
238
+ return this[dataResponseName];
239
+ },
240
+ WipeStates(storeKeyToRemove = null) {
241
+ const sptStateData = localStorage.getItem(StateNameUsedSoferList) ?? "{}";
242
+ let previousState = JSON.parse(sptStateData);
243
+ if (storeKeyToRemove)
244
+ delete previousState[storeKeyToRemove];
245
+ else
246
+ previousState = {};
247
+ const regroup = JSON.stringify(previousState);
248
+ localStorage.setItem(StateNameUsedSoferList, regroup);
249
+ },
250
+ async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0, reset: 0 } }, fasterDataCollection = null) {
251
+ this.Loading = true;
252
+ const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
253
+ const callApi = JSON.stringify(reqs);
254
+ const StateVariable = await this.parseData(StateStore, mStore);
255
+ this[StateStore] = StateVariable ?? [];
256
+ if (ds == null ? void 0 : ds.StateClean) {
257
+ const sptStateData = localStorage.getItem(StateNameUsedSoferList) ?? "{}";
258
+ const previousState = JSON.parse(sptStateData);
259
+ const stateKey = typeof StateStore === "string" ? StateStore : "septore-store-";
260
+ const regroup = JSON.stringify({ ...previousState, [storeId + "(-_+_-)" + stateKey]: StateStore });
261
+ localStorage.setItem(StateNameUsedSoferList, regroup);
262
+ }
263
+ if (this.StateValue[StateStore]) {
264
+ this.StateValue[StateStore] = false;
265
+ this[StateStore] = false;
266
+ }
267
+ if (this.CheckQueriesInQue[callApi]) {
268
+ console.warn(`************************************* dont call this api again ${reqs["url"]} \u{1F6E9}\uFE0F *************************************`, reqs);
269
+ return;
270
+ }
271
+ try {
272
+ const counters = this.validateObjectLength(StateVariable);
273
+ if (typeof fasterDataCollection == "function")
274
+ fasterDataCollection(StateVariable);
275
+ if (counters > 0) {
276
+ if (reload) {
277
+ const delay = await this.sleep(1e3 * time);
278
+ return await this.CallApiData(
279
+ StateStore,
280
+ callApi,
281
+ reqs,
282
+ pagnated,
283
+ mStore
284
+ );
285
+ }
286
+ this.Loading = false;
287
+ return this[StateStore];
288
+ } else {
289
+ this.Loading = true;
290
+ }
291
+ return await this.CallApiData(
292
+ StateStore,
293
+ callApi,
294
+ reqs,
295
+ pagnated,
296
+ mStore
297
+ );
298
+ } catch (error) {
299
+ if (this.CheckQueriesInQue[callApi])
300
+ delete this.CheckQueriesInQue[callApi];
301
+ }
302
+ },
303
+ Creator() {
304
+ if (typeof callBack === "function") {
305
+ return callBack(this);
306
+ }
307
+ },
308
+ DriveManual() {
309
+ return function() {
310
+ return this;
311
+ };
312
+ },
313
+ pagenatedData() {
314
+ }
315
+ }
316
+ });
317
+ return piniaData();
318
+ }
319
+ // Annotate the CommonJS export names for ESM import in node:
320
+ 0 && (module.exports = {
321
+ generateParams,
322
+ getBearerToken,
323
+ pomPinia,
324
+ setBearerToken,
325
+ useFetch
326
+ });
@@ -0,0 +1,311 @@
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
+ request.headers = {...(request?.headers??{}),} || {};
30
+ if (token)
31
+ request.headers.Authorization = `Bearer ${token}`;
32
+ // Handle FormData explicitly if needed
33
+ if (request.data instanceof FormData) {
34
+ const formData = request.data;
35
+ request.data = formData;
36
+ } else if (request.data) {
37
+ request.data = { ...(request.data ?? {}) };
38
+ }
39
+
40
+ return request;
41
+ };
42
+
43
+ // Response Interceptor
44
+ customAxios.interceptors.response.use(
45
+ (response) => response, // Resolve response as is
46
+ (error) => {
47
+ console.log("Error.....", error);
48
+ if (error.response?.status === 401) ;
49
+ return Promise.reject(error); // Reject the error for further handling
50
+ }
51
+ );
52
+
53
+ // Attach Request Interceptor
54
+ customAxios.interceptors.request.use(requestHandler, (error) =>
55
+ Promise.reject(error)
56
+ );
57
+
58
+ const useFetch = async ({ url, method, data }) => {
59
+ let _data = data ?? {};
60
+ try {
61
+ let response=null;
62
+ const uniformMethod = method.toLowerCase();
63
+ if (uniformMethod === 'get') {
64
+ const params = generateParams(_data ?? {});
65
+ response = await customAxios.get(`${url}${params}`);
66
+ } else
67
+ response = await customAxios.post(url, _data);
68
+
69
+ return response?.data ?? { Empty: 'Empty' };
70
+ } catch (err) {
71
+ console.error(err);
72
+ return { success: false, error: err };
73
+ }
74
+ };
75
+
76
+ const generateParams = (params={}) => {
77
+ try {
78
+
79
+ let data = "?";
80
+ for (let key in params) {
81
+ if (Object.hasOwnProperty.call(params, key)) {
82
+ if (params[key]) {
83
+ if (Array.isArray(params[key])) {
84
+ const elements = params[key] ;
85
+ for (const ele of elements) {
86
+ data += `${key}[]=${ele}&`;
87
+ }
88
+ } else {
89
+ data += `${key}=${params[key]}&`;
90
+ }
91
+ }
92
+ }
93
+ }
94
+ return data.slice(0, -1);
95
+ } catch (error) {
96
+ console.error(err);
97
+
98
+ }
99
+ };
100
+
101
+ function setBearerToken(name = { token: null }) {
102
+ if (typeof name !== "object" || name === null || Array.isArray(name))
103
+ throw new TypeError("setBearerToken expects an object {token} with a 'token' property.");
104
+
105
+ const tokenObj = { token: null, ...name,timestamp: Date.now() };
106
+ localStorage.setItem("logginToken", JSON.stringify(tokenObj));
107
+ }
108
+
109
+ function getBearerToken() {
110
+ const token = localStorage.getItem('logginToken');
111
+ try {
112
+ return token ? JSON.parse(token) : null;
113
+ } catch (e) {
114
+ console.error('Invalid token format in localStorage:', e);
115
+ return null;
116
+ }
117
+ }
118
+
119
+ function createPomStore( piniaStore = "7286204094", callBack=null,ds={StateClean:0}) {
120
+ const storeId = "POM" + piniaStore;
121
+ const StateNameUsedSoferList = "septor-store-collection"; const piniaData = defineStore(storeId, {
122
+ state: () => {
123
+ const StateObjectsContainer = {
124
+ CheckQueriesInQue: {},
125
+ StateValue: {},
126
+ Loading: true,
127
+ isThereAnyDataChangeInAform: false,
128
+ };
129
+
130
+ return StateObjectsContainer;
131
+ },
132
+
133
+ getters: {
134
+ stateItems: (state) => (TagetState) => {
135
+ /**
136
+ make data basing on state TagetState this acts as a clusure in ()() read about it
137
+ store.stateItems(key1) usage to ge the ge
138
+ **/
139
+ return (state[TagetState] = state[TagetState]);
140
+ },
141
+
142
+ },
143
+ actions: {
144
+ validateObjectLength(object) {
145
+ if (Array.isArray(object)) {
146
+ return object.length;
147
+ } else if (typeof object == "object") {
148
+ const lng = Object.keys(object);
149
+ return lng.length;
150
+ }
151
+ return 0;
152
+ },
153
+ pageNumber(pageUrl) {
154
+ const inputString = pageUrl; //'?page=124234232&&';
155
+ const regex = /\?(page)+=\d+/;
156
+ const match = regex.exec(inputString);
157
+
158
+ if (match) {
159
+ // /according to the patern ' i expect 1 value /
160
+ const matchedPattern = match[0];
161
+ const dataBack = matchedPattern
162
+ .split("?page=")
163
+ .join()
164
+ .replace(/[^\d]/, "");
165
+
166
+ return dataBack;
167
+ } else return "1";
168
+ },
169
+ sleep(timer) {
170
+ return new Promise((r) => setTimeout(r, timer));
171
+ },
172
+
173
+ async CallApiData( StateStore, callApi, dataParams, pagnated , mStore={} ) {
174
+ if (!this.CheckQueriesInQue[callApi]) {
175
+ this.CheckQueriesInQue[callApi] = callApi;
176
+ let [res] = await Promise.all([
177
+ useFetch (dataParams),
178
+ ]);
179
+
180
+ if (res) {
181
+ this[StateStore] = res;
182
+ if (mStore?.mUse) {
183
+ const checkType =typeof res === "object" ? JSON.stringify(res) : res;
184
+ sessionStorage.setItem(StateStore, JSON.stringify(checkType));
185
+ }
186
+
187
+ delete this.CheckQueriesInQue[callApi];
188
+ } else {
189
+ delete this.CheckQueriesInQue[callApi];
190
+ console.error(res);
191
+ }
192
+ this.Loading = false;
193
+ return res;
194
+ }
195
+ this.Loading = false;
196
+ return this[StateStore] ?? [];
197
+ },
198
+ async parseData(
199
+ dataResponseName = "xxx",
200
+ mStore = { mUse: false, reset: false }
201
+ ) {
202
+ try {
203
+ if (mStore?.reset) {
204
+ sessionStorage.removeItem(dataResponseName);
205
+ }
206
+
207
+ if (mStore?.mUse) {
208
+ const thisData = JSON.parse(JSON.parse(sessionStorage.getItem(dataResponseName) || {}));
209
+ return thisData;
210
+ }
211
+ } catch (error) {}
212
+
213
+ return this[dataResponseName];
214
+ },
215
+ WipeStates(storeKeyToRemove=null){
216
+ const sptStateData = localStorage.getItem(StateNameUsedSoferList) ?? "{}";
217
+ let previousState = JSON.parse(sptStateData);
218
+ if (storeKeyToRemove)
219
+ delete previousState[storeKeyToRemove];
220
+ else
221
+ previousState={};
222
+
223
+ const regroup = JSON.stringify(previousState);
224
+ localStorage.setItem(StateNameUsedSoferList, regroup);
225
+ },
226
+ async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0,reset:0 },},fasterDataCollection=null) {
227
+ this.Loading = true;
228
+ const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
229
+ const callApi = JSON.stringify(reqs);
230
+ const StateVariable = await this.parseData(StateStore, mStore);
231
+ this[StateStore] = StateVariable ?? [];
232
+ if (ds?.StateClean) {
233
+ const sptStateData =localStorage.getItem(StateNameUsedSoferList) ?? "{}";
234
+ const previousState = JSON.parse(sptStateData);
235
+ const stateKey = typeof StateStore === "string" ? StateStore : "septore-store-";
236
+ const regroup = JSON.stringify({...previousState,[storeId + "(-_+_-)" + stateKey]: StateStore,});
237
+ localStorage.setItem(StateNameUsedSoferList, regroup);
238
+ }
239
+ if (this.StateValue[StateStore]) {
240
+ /**
241
+ * dynamically lets create the state store
242
+ **/
243
+ this.StateValue[StateStore] = false;
244
+ this[StateStore] = false;
245
+ // this[StateStore] =null ;
246
+ }
247
+
248
+ if (this.CheckQueriesInQue[callApi]) {
249
+ console.warn(`************************************* dont call this api again ${reqs["url"]} 🛩️ *************************************`,reqs);
250
+ return;
251
+ }
252
+ try {
253
+ const counters = this.validateObjectLength(StateVariable);
254
+ if (typeof fasterDataCollection == "function")
255
+ fasterDataCollection(StateVariable);
256
+
257
+ if (counters > 0) {
258
+ if (reload) {
259
+ const delay = await this.sleep(1000 * time);
260
+ return await this.CallApiData(
261
+ StateStore,
262
+ callApi,
263
+ reqs,
264
+ pagnated,
265
+ mStore
266
+ );
267
+ }
268
+
269
+ this.Loading = false;
270
+ return this[StateStore];
271
+ } else {
272
+ this.Loading = true;
273
+ }
274
+
275
+ return await this.CallApiData(
276
+ StateStore,
277
+ callApi,
278
+ reqs,
279
+ pagnated,
280
+ mStore
281
+ );
282
+ } catch (error) {
283
+ // console.error(error);
284
+ if (this.CheckQueriesInQue[callApi])
285
+ delete this.CheckQueriesInQue[callApi];
286
+ }
287
+ },
288
+ Creator() {
289
+ /**
290
+ *
291
+ * this will retun a call back wth the full object
292
+ * **/
293
+ if (typeof callBack === "function") {
294
+ return callBack(this);
295
+ }
296
+ },
297
+ DriveManual() {
298
+ return function () {
299
+ return this;
300
+ };
301
+ },
302
+ pagenatedData() {},
303
+ },
304
+ });
305
+
306
+ return piniaData();
307
+ }
308
+
309
+ // module.e = createPomStore
310
+
311
+ export { generateParams, getBearerToken, createPomStore as pomPinia, setBearerToken, useFetch };
@@ -0,0 +1,311 @@
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
+ request.headers = {...(request?.headers??{}),} || {};
30
+ if (token)
31
+ request.headers.Authorization = `Bearer ${token}`;
32
+ // Handle FormData explicitly if needed
33
+ if (request.data instanceof FormData) {
34
+ const formData = request.data;
35
+ request.data = formData;
36
+ } else if (request.data) {
37
+ request.data = { ...(request.data ?? {}) };
38
+ }
39
+
40
+ return request;
41
+ };
42
+
43
+ // Response Interceptor
44
+ customAxios.interceptors.response.use(
45
+ (response) => response, // Resolve response as is
46
+ (error) => {
47
+ console.log("Error.....", error);
48
+ if (error.response?.status === 401) ;
49
+ return Promise.reject(error); // Reject the error for further handling
50
+ }
51
+ );
52
+
53
+ // Attach Request Interceptor
54
+ customAxios.interceptors.request.use(requestHandler, (error) =>
55
+ Promise.reject(error)
56
+ );
57
+
58
+ const useFetch = async ({ url, method, data }) => {
59
+ let _data = data ?? {};
60
+ try {
61
+ let response=null;
62
+ const uniformMethod = method.toLowerCase();
63
+ if (uniformMethod === 'get') {
64
+ const params = generateParams(_data ?? {});
65
+ response = await customAxios.get(`${url}${params}`);
66
+ } else
67
+ response = await customAxios.post(url, _data);
68
+
69
+ return response?.data ?? { Empty: 'Empty' };
70
+ } catch (err) {
71
+ console.error(err);
72
+ return { success: false, error: err };
73
+ }
74
+ };
75
+
76
+ const generateParams = (params={}) => {
77
+ try {
78
+
79
+ let data = "?";
80
+ for (let key in params) {
81
+ if (Object.hasOwnProperty.call(params, key)) {
82
+ if (params[key]) {
83
+ if (Array.isArray(params[key])) {
84
+ const elements = params[key] ;
85
+ for (const ele of elements) {
86
+ data += `${key}[]=${ele}&`;
87
+ }
88
+ } else {
89
+ data += `${key}=${params[key]}&`;
90
+ }
91
+ }
92
+ }
93
+ }
94
+ return data.slice(0, -1);
95
+ } catch (error) {
96
+ console.error(err);
97
+
98
+ }
99
+ };
100
+
101
+ function setBearerToken(name = { token: null }) {
102
+ if (typeof name !== "object" || name === null || Array.isArray(name))
103
+ throw new TypeError("setBearerToken expects an object {token} with a 'token' property.");
104
+
105
+ const tokenObj = { token: null, ...name,timestamp: Date.now() };
106
+ localStorage.setItem("logginToken", JSON.stringify(tokenObj));
107
+ }
108
+
109
+ function getBearerToken() {
110
+ const token = localStorage.getItem('logginToken');
111
+ try {
112
+ return token ? JSON.parse(token) : null;
113
+ } catch (e) {
114
+ console.error('Invalid token format in localStorage:', e);
115
+ return null;
116
+ }
117
+ }
118
+
119
+ function createPomStore( piniaStore = "7286204094", callBack=null,ds={StateClean:0}) {
120
+ const storeId = "POM" + piniaStore;
121
+ const StateNameUsedSoferList = "septor-store-collection"; const piniaData = defineStore(storeId, {
122
+ state: () => {
123
+ const StateObjectsContainer = {
124
+ CheckQueriesInQue: {},
125
+ StateValue: {},
126
+ Loading: true,
127
+ isThereAnyDataChangeInAform: false,
128
+ };
129
+
130
+ return StateObjectsContainer;
131
+ },
132
+
133
+ getters: {
134
+ stateItems: (state) => (TagetState) => {
135
+ /**
136
+ make data basing on state TagetState this acts as a clusure in ()() read about it
137
+ store.stateItems(key1) usage to ge the ge
138
+ **/
139
+ return (state[TagetState] = state[TagetState]);
140
+ },
141
+
142
+ },
143
+ actions: {
144
+ validateObjectLength(object) {
145
+ if (Array.isArray(object)) {
146
+ return object.length;
147
+ } else if (typeof object == "object") {
148
+ const lng = Object.keys(object);
149
+ return lng.length;
150
+ }
151
+ return 0;
152
+ },
153
+ pageNumber(pageUrl) {
154
+ const inputString = pageUrl; //'?page=124234232&&';
155
+ const regex = /\?(page)+=\d+/;
156
+ const match = regex.exec(inputString);
157
+
158
+ if (match) {
159
+ // /according to the patern ' i expect 1 value /
160
+ const matchedPattern = match[0];
161
+ const dataBack = matchedPattern
162
+ .split("?page=")
163
+ .join()
164
+ .replace(/[^\d]/, "");
165
+
166
+ return dataBack;
167
+ } else return "1";
168
+ },
169
+ sleep(timer) {
170
+ return new Promise((r) => setTimeout(r, timer));
171
+ },
172
+
173
+ async CallApiData( StateStore, callApi, dataParams, pagnated , mStore={} ) {
174
+ if (!this.CheckQueriesInQue[callApi]) {
175
+ this.CheckQueriesInQue[callApi] = callApi;
176
+ let [res] = await Promise.all([
177
+ useFetch (dataParams),
178
+ ]);
179
+
180
+ if (res) {
181
+ this[StateStore] = res;
182
+ if (mStore?.mUse) {
183
+ const checkType =typeof res === "object" ? JSON.stringify(res) : res;
184
+ sessionStorage.setItem(StateStore, JSON.stringify(checkType));
185
+ }
186
+
187
+ delete this.CheckQueriesInQue[callApi];
188
+ } else {
189
+ delete this.CheckQueriesInQue[callApi];
190
+ console.error(res);
191
+ }
192
+ this.Loading = false;
193
+ return res;
194
+ }
195
+ this.Loading = false;
196
+ return this[StateStore] ?? [];
197
+ },
198
+ async parseData(
199
+ dataResponseName = "xxx",
200
+ mStore = { mUse: false, reset: false }
201
+ ) {
202
+ try {
203
+ if (mStore?.reset) {
204
+ sessionStorage.removeItem(dataResponseName);
205
+ }
206
+
207
+ if (mStore?.mUse) {
208
+ const thisData = JSON.parse(JSON.parse(sessionStorage.getItem(dataResponseName) || {}));
209
+ return thisData;
210
+ }
211
+ } catch (error) {}
212
+
213
+ return this[dataResponseName];
214
+ },
215
+ WipeStates(storeKeyToRemove=null){
216
+ const sptStateData = localStorage.getItem(StateNameUsedSoferList) ?? "{}";
217
+ let previousState = JSON.parse(sptStateData);
218
+ if (storeKeyToRemove)
219
+ delete previousState[storeKeyToRemove];
220
+ else
221
+ previousState={};
222
+
223
+ const regroup = JSON.stringify(previousState);
224
+ localStorage.setItem(StateNameUsedSoferList, regroup);
225
+ },
226
+ async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0,reset:0 },},fasterDataCollection=null) {
227
+ this.Loading = true;
228
+ const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
229
+ const callApi = JSON.stringify(reqs);
230
+ const StateVariable = await this.parseData(StateStore, mStore);
231
+ this[StateStore] = StateVariable ?? [];
232
+ if (ds?.StateClean) {
233
+ const sptStateData =localStorage.getItem(StateNameUsedSoferList) ?? "{}";
234
+ const previousState = JSON.parse(sptStateData);
235
+ const stateKey = typeof StateStore === "string" ? StateStore : "septore-store-";
236
+ const regroup = JSON.stringify({...previousState,[storeId + "(-_+_-)" + stateKey]: StateStore,});
237
+ localStorage.setItem(StateNameUsedSoferList, regroup);
238
+ }
239
+ if (this.StateValue[StateStore]) {
240
+ /**
241
+ * dynamically lets create the state store
242
+ **/
243
+ this.StateValue[StateStore] = false;
244
+ this[StateStore] = false;
245
+ // this[StateStore] =null ;
246
+ }
247
+
248
+ if (this.CheckQueriesInQue[callApi]) {
249
+ console.warn(`************************************* dont call this api again ${reqs["url"]} 🛩️ *************************************`,reqs);
250
+ return;
251
+ }
252
+ try {
253
+ const counters = this.validateObjectLength(StateVariable);
254
+ if (typeof fasterDataCollection == "function")
255
+ fasterDataCollection(StateVariable);
256
+
257
+ if (counters > 0) {
258
+ if (reload) {
259
+ const delay = await this.sleep(1000 * time);
260
+ return await this.CallApiData(
261
+ StateStore,
262
+ callApi,
263
+ reqs,
264
+ pagnated,
265
+ mStore
266
+ );
267
+ }
268
+
269
+ this.Loading = false;
270
+ return this[StateStore];
271
+ } else {
272
+ this.Loading = true;
273
+ }
274
+
275
+ return await this.CallApiData(
276
+ StateStore,
277
+ callApi,
278
+ reqs,
279
+ pagnated,
280
+ mStore
281
+ );
282
+ } catch (error) {
283
+ // console.error(error);
284
+ if (this.CheckQueriesInQue[callApi])
285
+ delete this.CheckQueriesInQue[callApi];
286
+ }
287
+ },
288
+ Creator() {
289
+ /**
290
+ *
291
+ * this will retun a call back wth the full object
292
+ * **/
293
+ if (typeof callBack === "function") {
294
+ return callBack(this);
295
+ }
296
+ },
297
+ DriveManual() {
298
+ return function () {
299
+ return this;
300
+ };
301
+ },
302
+ pagenatedData() {},
303
+ },
304
+ });
305
+
306
+ return piniaData();
307
+ }
308
+
309
+ // module.e = createPomStore
310
+
311
+ export { generateParams, getBearerToken, createPomStore as pomPinia, setBearerToken, useFetch };
package/dist/index.js ADDED
@@ -0,0 +1,285 @@
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
+ request.headers = { ...(request == null ? void 0 : request.headers) ?? {} };
39
+ if (token)
40
+ request.headers.Authorization = `Bearer ${token}`;
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, ds = { StateClean: 0 }) {
123
+ const storeId = "POM" + piniaStore;
124
+ const StateNameUsedSoferList = "septor-store-collection";
125
+ ;
126
+ const piniaData = defineStore(storeId, {
127
+ state: () => {
128
+ const StateObjectsContainer = {
129
+ CheckQueriesInQue: {},
130
+ StateValue: {},
131
+ Loading: true,
132
+ isThereAnyDataChangeInAform: false
133
+ };
134
+ return StateObjectsContainer;
135
+ },
136
+ getters: {
137
+ stateItems: (state) => (TagetState) => {
138
+ return state[TagetState] = state[TagetState];
139
+ }
140
+ },
141
+ actions: {
142
+ validateObjectLength(object) {
143
+ if (Array.isArray(object)) {
144
+ return object.length;
145
+ } else if (typeof object == "object") {
146
+ const lng = Object.keys(object);
147
+ return lng.length;
148
+ }
149
+ return 0;
150
+ },
151
+ pageNumber(pageUrl) {
152
+ const inputString = pageUrl;
153
+ const regex = /\?(page)+=\d+/;
154
+ const match = regex.exec(inputString);
155
+ if (match) {
156
+ const matchedPattern = match[0];
157
+ const dataBack = matchedPattern.split("?page=").join().replace(/[^\d]/, "");
158
+ return dataBack;
159
+ } else return "1";
160
+ },
161
+ sleep(timer) {
162
+ return new Promise((r) => setTimeout(r, timer));
163
+ },
164
+ async CallApiData(StateStore, callApi, dataParams, pagnated, mStore = {}) {
165
+ if (!this.CheckQueriesInQue[callApi]) {
166
+ this.CheckQueriesInQue[callApi] = callApi;
167
+ let [res] = await Promise.all([
168
+ useFetch(dataParams)
169
+ ]);
170
+ if (res) {
171
+ this[StateStore] = res;
172
+ if (mStore == null ? void 0 : mStore.mUse) {
173
+ const checkType = typeof res === "object" ? JSON.stringify(res) : res;
174
+ sessionStorage.setItem(StateStore, JSON.stringify(checkType));
175
+ }
176
+ delete this.CheckQueriesInQue[callApi];
177
+ } else {
178
+ delete this.CheckQueriesInQue[callApi];
179
+ console.error(res);
180
+ }
181
+ this.Loading = false;
182
+ return res;
183
+ }
184
+ this.Loading = false;
185
+ return this[StateStore] ?? [];
186
+ },
187
+ async parseData(dataResponseName = "xxx", mStore = { mUse: false, reset: false }) {
188
+ try {
189
+ if (mStore == null ? void 0 : mStore.reset) {
190
+ sessionStorage.removeItem(dataResponseName);
191
+ }
192
+ if (mStore == null ? void 0 : mStore.mUse) {
193
+ const thisData = JSON.parse(JSON.parse(sessionStorage.getItem(dataResponseName) || {}));
194
+ return thisData;
195
+ }
196
+ } catch (error) {
197
+ }
198
+ return this[dataResponseName];
199
+ },
200
+ WipeStates(storeKeyToRemove = null) {
201
+ const sptStateData = localStorage.getItem(StateNameUsedSoferList) ?? "{}";
202
+ let previousState = JSON.parse(sptStateData);
203
+ if (storeKeyToRemove)
204
+ delete previousState[storeKeyToRemove];
205
+ else
206
+ previousState = {};
207
+ const regroup = JSON.stringify(previousState);
208
+ localStorage.setItem(StateNameUsedSoferList, regroup);
209
+ },
210
+ async stateGenaratorApi(dd = { reload: true, StateStore: "", reqs: {}, time: 0, pagnated: false, mStore: { mUse: 0, reset: 0 } }, fasterDataCollection = null) {
211
+ this.Loading = true;
212
+ const { reload, StateStore, reqs, time, pagnated, mStore } = dd;
213
+ const callApi = JSON.stringify(reqs);
214
+ const StateVariable = await this.parseData(StateStore, mStore);
215
+ this[StateStore] = StateVariable ?? [];
216
+ if (ds == null ? void 0 : ds.StateClean) {
217
+ const sptStateData = localStorage.getItem(StateNameUsedSoferList) ?? "{}";
218
+ const previousState = JSON.parse(sptStateData);
219
+ const stateKey = typeof StateStore === "string" ? StateStore : "septore-store-";
220
+ const regroup = JSON.stringify({ ...previousState, [storeId + "(-_+_-)" + stateKey]: StateStore });
221
+ localStorage.setItem(StateNameUsedSoferList, regroup);
222
+ }
223
+ if (this.StateValue[StateStore]) {
224
+ this.StateValue[StateStore] = false;
225
+ this[StateStore] = false;
226
+ }
227
+ if (this.CheckQueriesInQue[callApi]) {
228
+ console.warn(`************************************* dont call this api again ${reqs["url"]} \u{1F6E9}\uFE0F *************************************`, reqs);
229
+ return;
230
+ }
231
+ try {
232
+ const counters = this.validateObjectLength(StateVariable);
233
+ if (typeof fasterDataCollection == "function")
234
+ fasterDataCollection(StateVariable);
235
+ if (counters > 0) {
236
+ if (reload) {
237
+ const delay = await this.sleep(1e3 * time);
238
+ return await this.CallApiData(
239
+ StateStore,
240
+ callApi,
241
+ reqs,
242
+ pagnated,
243
+ mStore
244
+ );
245
+ }
246
+ this.Loading = false;
247
+ return this[StateStore];
248
+ } else {
249
+ this.Loading = true;
250
+ }
251
+ return await this.CallApiData(
252
+ StateStore,
253
+ callApi,
254
+ reqs,
255
+ pagnated,
256
+ mStore
257
+ );
258
+ } catch (error) {
259
+ if (this.CheckQueriesInQue[callApi])
260
+ delete this.CheckQueriesInQue[callApi];
261
+ }
262
+ },
263
+ Creator() {
264
+ if (typeof callBack === "function") {
265
+ return callBack(this);
266
+ }
267
+ },
268
+ DriveManual() {
269
+ return function() {
270
+ return this;
271
+ };
272
+ },
273
+ pagenatedData() {
274
+ }
275
+ }
276
+ });
277
+ return piniaData();
278
+ }
279
+ export {
280
+ generateParams,
281
+ getBearerToken,
282
+ createPomStore as pomPinia,
283
+ setBearerToken,
284
+ useFetch
285
+ };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
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": "1.0.0",
6
+ "version": "1.0.2",
7
7
  "type": "module",
8
8
  "main": "dist/index.cjs",
9
9
  "module": "dist/index.js",
@@ -71,7 +71,7 @@
71
71
  "author": "Ssengendo Nazil",
72
72
  "repository": {
73
73
  "type": "git",
74
- "url": "https://github.com/ssengedonazil/septor-store-testing.git"
74
+ "url": "git+https://github.com/ssengedonazil/septor-store-testing.git"
75
75
  },
76
76
  "bugs": {
77
77
  "url": "https://github.com/ssengedonazil/septor-store-testing.git/issues"