@communecter/cocolight-api-client 1.0.17 → 1.0.19

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.
@@ -0,0 +1,131 @@
1
+ // MultiServerTokenStorageStrategy.js
2
+ import { TokenStorageStrategy } from "./TokenStorage.js";
3
+
4
+ export class MultiServerTokenStorageStrategy extends TokenStorageStrategy {
5
+ constructor() {
6
+ super();
7
+ this._currentBaseURL = null;
8
+ }
9
+
10
+ use(baseURL) {
11
+ if (!baseURL) throw new Error("baseURL est requis");
12
+ this._currentBaseURL = baseURL.replace(/\/+$/, "");
13
+ }
14
+
15
+ _ensureContext() {
16
+ if (!this._currentBaseURL) throw new Error("baseURL non défini. Appelez use(baseURL)");
17
+ }
18
+
19
+ getServers() {
20
+ throw new Error("getServers() doit être implémenté");
21
+ }
22
+
23
+ exportAll() {
24
+ throw new Error("exportAll() doit être implémenté");
25
+ }
26
+ }
27
+
28
+ // Mémoire
29
+ export class MultiServerMemoryStorageStrategy extends MultiServerTokenStorageStrategy {
30
+ constructor() {
31
+ super();
32
+ this._storage = new Map();
33
+ }
34
+
35
+ getAccessToken() {
36
+ this._ensureContext();
37
+ return this._storage.get(this._currentBaseURL)?.accessToken || null;
38
+ }
39
+
40
+ setAccessToken(token) {
41
+ this._ensureContext();
42
+ const current = this._storage.get(this._currentBaseURL) || {};
43
+ this._storage.set(this._currentBaseURL, { ...current, accessToken: token });
44
+ }
45
+
46
+ getRefreshToken() {
47
+ this._ensureContext();
48
+ return this._storage.get(this._currentBaseURL)?.refreshToken || null;
49
+ }
50
+
51
+ setRefreshToken(token) {
52
+ this._ensureContext();
53
+ const current = this._storage.get(this._currentBaseURL) || {};
54
+ this._storage.set(this._currentBaseURL, { ...current, refreshToken: token });
55
+ }
56
+
57
+ clear() {
58
+ this._ensureContext();
59
+ this._storage.delete(this._currentBaseURL);
60
+ }
61
+
62
+ getServers() {
63
+ return [...this._storage.keys()];
64
+ }
65
+
66
+ exportAll() {
67
+ return Object.fromEntries(this._storage.entries());
68
+ }
69
+ }
70
+
71
+ // Navigateur (localStorage)
72
+ export class MultiServerLocalStorageStrategy extends MultiServerTokenStorageStrategy {
73
+ constructor(prefix = "cocolight") {
74
+ super();
75
+ this.prefix = prefix;
76
+ }
77
+
78
+ _key(baseURL) {
79
+ return `${this.prefix}_tokens_${baseURL}`;
80
+ }
81
+
82
+ _getData() {
83
+ this._ensureContext();
84
+ const raw = localStorage.getItem(this._key(this._currentBaseURL));
85
+ return raw ? JSON.parse(raw) : {};
86
+ }
87
+
88
+ _setData(data) {
89
+ localStorage.setItem(this._key(this._currentBaseURL), JSON.stringify(data));
90
+ }
91
+
92
+ getAccessToken() {
93
+ return this._getData().accessToken || null;
94
+ }
95
+
96
+ setAccessToken(token) {
97
+ const data = this._getData();
98
+ data.accessToken = token;
99
+ this._setData(data);
100
+ }
101
+
102
+ getRefreshToken() {
103
+ return this._getData().refreshToken || null;
104
+ }
105
+
106
+ setRefreshToken(token) {
107
+ const data = this._getData();
108
+ data.refreshToken = token;
109
+ this._setData(data);
110
+ }
111
+
112
+ clear() {
113
+ localStorage.removeItem(this._key(this._currentBaseURL));
114
+ }
115
+
116
+ getServers() {
117
+ const keys = Object.keys(localStorage);
118
+ return keys
119
+ .filter(k => k.startsWith(`${this.prefix}_tokens_`))
120
+ .map(k => k.replace(`${this.prefix}_tokens_`, ""));
121
+ }
122
+
123
+ exportAll() {
124
+ const result = {};
125
+ for (const baseURL of this.getServers()) {
126
+ const raw = localStorage.getItem(this._key(baseURL));
127
+ if (raw) result[baseURL] = JSON.parse(raw);
128
+ }
129
+ return result;
130
+ }
131
+ }
@@ -0,0 +1,45 @@
1
+ import {
2
+ MultiServerMemoryStorageStrategy,
3
+ MultiServerLocalStorageStrategy,
4
+ } from "./MultiServerTokenStorageStrategy.js";
5
+
6
+ /**
7
+ * Crée une stratégie de stockage de tokens multi-serveurs adaptée à l’environnement.
8
+ *
9
+ * @param {string} [strategyType="auto"] - Type de stockage souhaité :
10
+ * - "memory" : en mémoire (non persistant)
11
+ * - "localStorage" : navigateur uniquement
12
+ * - "file" : Node.js uniquement
13
+ * - "auto" : choisit automatiquement selon l’environnement
14
+ * @returns {Promise<MultiServerTokenStorageStrategy>}
15
+ */
16
+ export async function createDefaultMultiServerTokenStorageStrategy(strategyType = "auto") {
17
+ if (strategyType === "memory") {
18
+ return new MultiServerMemoryStorageStrategy();
19
+ }
20
+
21
+ if (strategyType === "localStorage") {
22
+ if (typeof window !== "undefined" && window.localStorage) {
23
+ return new MultiServerLocalStorageStrategy();
24
+ } else {
25
+ throw new Error("localStorage n’est pas disponible dans cet environnement.");
26
+ }
27
+ }
28
+
29
+ if (strategyType === "file") {
30
+ if (typeof window !== "undefined" && window.localStorage) {
31
+ throw new Error("Le stockage fichier n’est pas disponible côté navigateur.");
32
+ }
33
+ const { MultiServerFileStorageStrategy } = await import("./MultiServerFileStorageStrategy.node.js");
34
+ return new MultiServerFileStorageStrategy();
35
+ }
36
+
37
+ // stratégie "auto"
38
+ if (typeof window !== "undefined" && window.localStorage) {
39
+ return new MultiServerLocalStorageStrategy();
40
+ } else {
41
+ const { MultiServerFileStorageStrategy } = await import("./MultiServerTokenStorageStrategy.js");
42
+ return new MultiServerFileStorageStrategy();
43
+ }
44
+ }
45
+
@@ -1,7 +1,5 @@
1
1
  import { LocalStorageStrategy, MemoryStorageStrategy } from "./TokenStorage.js";
2
2
 
3
- // src/utils/createDefaultTokenStorageStrategy.js
4
-
5
3
  /**
6
4
  * Crée une stratégie de stockage de jetons par défaut en fonction de l'option fournie.
7
5
  *
@@ -1,42 +0,0 @@
1
- import { ApiResponseError } from "../error.js";
2
-
3
- // NewsMixin.js
4
- export const NewsMixin = {
5
- /**
6
- * Récupérer les actualités : Récupère la liste d’actualités selon plusieurs critères.
7
- * Constant : GET_NEWS
8
- * @param {Object} data - Les données à envoyer.
9
- * @param {number} data.dateLimit - Limite de date timestamp ou 0 (default: 0)
10
- * @param {object} data.search - data.search
11
- * @param {string} data.search.name - Nom ou terme recherché (default: "")
12
- * @param {number} data.indexStep - Nombre de résultats par page (default: 12)
13
- * @returns {Promise<Object>} - Les données de réponse.
14
- * @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
15
- * @throws {Error} - En cas d'erreur inattendue.
16
- */
17
- async getNews(data = {}) {
18
- data.pathParams = { type: this.getEntityType(), id: this.id };
19
- const arrayObjetNews = await this.endpointApi.getNews(data);
20
- if(!Array.isArray(arrayObjetNews)){
21
- throw new ApiResponseError("Erreur lors de la récupération des actualités.", 500, arrayObjetNews);
22
- }
23
- const rawNewsList = arrayObjetNews.map((newsData) =>
24
- this.deps.News.fromServerData(newsData, this, { User : this.deps.User, EndpointApi: this.deps.EndpointApi })
25
- );
26
- return this._createFilteredProxy(rawNewsList);
27
- },
28
-
29
- async news(newsData) {
30
- try {
31
- const news = new this.deps.News(this, newsData, { User: this.deps.User, EndpointApi : this.deps.EndpointApi });
32
- if (newsData.id) {
33
- await news.get();
34
- }
35
- return news;
36
- } catch (error) {
37
- this.apiClient._logger.error(`[Api.${this.getEntityType()}.news] Erreur lors de la création d'une instance news :`, error.message);
38
- throw error;
39
- }
40
- }
41
- };
42
-