@communecter/cocolight-api-client 1.0.54 → 1.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/dist/401.cocolight-api-client.browser.js +1 -0
  2. package/dist/401.cocolight-api-client.cjs +1 -0
  3. package/dist/401.cocolight-api-client.mjs.js +1 -0
  4. package/dist/588.cocolight-api-client.browser.js +1 -0
  5. package/dist/588.cocolight-api-client.cjs +1 -0
  6. package/dist/588.cocolight-api-client.mjs.js +1 -0
  7. package/dist/593.cocolight-api-client.browser.js +1 -0
  8. package/dist/593.cocolight-api-client.cjs +1 -0
  9. package/dist/593.cocolight-api-client.mjs.js +1 -0
  10. package/dist/839.cocolight-api-client.browser.js +1 -0
  11. package/dist/839.cocolight-api-client.cjs +1 -0
  12. package/dist/839.cocolight-api-client.mjs.js +1 -0
  13. package/dist/cocolight-api-client.browser.js +3 -3
  14. package/dist/cocolight-api-client.cjs +1 -1
  15. package/dist/cocolight-api-client.mjs.js +1 -1
  16. package/dist/cocolight-api-client.vite.mjs.js +1 -1
  17. package/dist/cocolight-api-client.vite.mjs.js.map +1 -1
  18. package/package.json +29 -17
  19. package/src/{Api.js → Api.ts} +85 -95
  20. package/src/{ApiClient.js → ApiClient.ts} +436 -247
  21. package/src/EJSONType.ts +103 -0
  22. package/src/api/{Badge.js → Badge.ts} +56 -45
  23. package/src/api/BaseEntity.ts +3890 -0
  24. package/src/api/Comment.ts +200 -0
  25. package/src/api/{EndpointApi.js → EndpointApi.ts} +363 -297
  26. package/src/api/EndpointApi.types.ts +4609 -0
  27. package/src/api/EntityRegistry.ts +203 -0
  28. package/src/api/Event.ts +332 -0
  29. package/src/api/News.ts +331 -0
  30. package/src/api/{Organization.js → Organization.ts} +155 -119
  31. package/src/api/{Poi.js → Poi.ts} +68 -60
  32. package/src/api/{Project.js → Project.ts} +150 -127
  33. package/src/api/{User.js → User.ts} +321 -256
  34. package/src/api/UserApi.ts +148 -0
  35. package/src/api/serverDataType/Comment.ts +88 -0
  36. package/src/api/serverDataType/Event.ts +80 -0
  37. package/src/api/serverDataType/News.ts +138 -0
  38. package/src/api/serverDataType/Organization.ts +80 -0
  39. package/src/api/serverDataType/Project.ts +71 -0
  40. package/src/api/serverDataType/User.ts +103 -0
  41. package/src/api/serverDataType/common.ts +80 -0
  42. package/src/endpoints.module.ts +2621 -0
  43. package/src/error.ts +86 -0
  44. package/src/index.ts +86 -0
  45. package/src/mixin/UserMixin.ts +4 -0
  46. package/src/types/api-responses.ts +217 -0
  47. package/src/types/entities.ts +22 -0
  48. package/src/types/error-guards.ts +230 -0
  49. package/src/types/index.ts +39 -0
  50. package/src/types/payloads.ts +21 -0
  51. package/src/types/transforms.ts +110 -0
  52. package/src/utils/{FileOfflineStorageStrategy.node.js → FileOfflineStorageStrategy.node.ts} +15 -12
  53. package/src/utils/{FileStorageStrategy.node.js → FileStorageStrategy.node.ts} +16 -39
  54. package/src/utils/MultiServerFileStorageStrategy.node.ts +67 -0
  55. package/src/utils/MultiServerTokenStorageStrategy.ts +139 -0
  56. package/src/utils/{OfflineClientManager.js → OfflineClientManager.ts} +82 -86
  57. package/src/utils/OfflineQueueStorageStrategy.ts +47 -0
  58. package/src/utils/TokenStorage.ts +77 -0
  59. package/src/utils/compat.ts +12 -0
  60. package/src/utils/createDefaultMultiServerTokenStorageStrategy.ts +35 -0
  61. package/src/utils/{createDefaultOfflineStrategy.js → createDefaultOfflineStrategy.ts} +8 -3
  62. package/src/utils/createDefaultTokenStorageStrategy.ts +33 -0
  63. package/src/utils/{reactive.js → reactive.ts} +49 -40
  64. package/src/utils/stream-utils.node.ts +12 -0
  65. package/types/Api.d.ts +38 -82
  66. package/types/Api.d.ts.map +1 -0
  67. package/types/ApiClient.d.ts +244 -184
  68. package/types/ApiClient.d.ts.map +1 -0
  69. package/types/EJSONType.d.ts +48 -22
  70. package/types/EJSONType.d.ts.map +1 -0
  71. package/types/api/Badge.d.ts +20 -20
  72. package/types/api/Badge.d.ts.map +1 -0
  73. package/types/api/BaseEntity.d.ts +751 -446
  74. package/types/api/BaseEntity.d.ts.map +1 -0
  75. package/types/api/Comment.d.ts +36 -0
  76. package/types/api/EndpointApi.d.ts +347 -295
  77. package/types/api/EndpointApi.d.ts.map +1 -0
  78. package/types/api/EndpointApi.types.d.ts +3914 -4133
  79. package/types/api/EntityRegistry.d.ts +18 -16
  80. package/types/api/EntityRegistry.d.ts.map +1 -0
  81. package/types/api/Event.d.ts +119 -35
  82. package/types/api/Event.d.ts.map +1 -0
  83. package/types/api/News.d.ts +52 -20
  84. package/types/api/News.d.ts.map +1 -0
  85. package/types/api/Organization.d.ts +165 -49
  86. package/types/api/Organization.d.ts.map +1 -0
  87. package/types/api/Poi.d.ts +51 -22
  88. package/types/api/Poi.d.ts.map +1 -0
  89. package/types/api/Project.d.ts +151 -52
  90. package/types/api/Project.d.ts.map +1 -0
  91. package/types/api/User.d.ts +222 -93
  92. package/types/api/User.d.ts.map +1 -0
  93. package/types/api/UserApi.d.ts +60 -9
  94. package/types/api/UserApi.d.ts.map +1 -0
  95. package/types/api/serverDataType/Comment.d.ts +83 -0
  96. package/types/api/serverDataType/Event.d.ts +67 -0
  97. package/types/api/serverDataType/News.d.ts +130 -0
  98. package/types/api/serverDataType/Organization.d.ts +65 -0
  99. package/types/api/serverDataType/Organization.d.ts.map +1 -0
  100. package/types/api/serverDataType/Project.d.ts +58 -0
  101. package/types/api/serverDataType/Project.d.ts.map +1 -0
  102. package/types/api/serverDataType/User.d.ts +86 -0
  103. package/types/api/serverDataType/User.d.ts.map +1 -0
  104. package/types/api/serverDataType/common.d.ts +71 -0
  105. package/types/api/serverDataType/common.d.ts.map +1 -0
  106. package/types/endpoints.module.d.ts +6922 -1215
  107. package/types/endpoints.module.d.ts.map +1 -0
  108. package/types/error.d.ts +25 -51
  109. package/types/error.d.ts.map +1 -0
  110. package/types/index.d.ts +55 -48
  111. package/types/index.d.ts.map +1 -0
  112. package/types/mixin/UserMixin.d.ts +1 -1
  113. package/types/mixin/UserMixin.d.ts.map +1 -0
  114. package/types/types/api-responses.d.ts +190 -0
  115. package/types/types/api-responses.d.ts.map +1 -0
  116. package/types/types/entities.d.ts +17 -0
  117. package/types/types/entities.d.ts.map +1 -0
  118. package/types/types/error-guards.d.ts +99 -0
  119. package/types/types/error-guards.d.ts.map +1 -0
  120. package/types/types/index.d.ts +7 -0
  121. package/types/types/payloads.d.ts +17 -0
  122. package/types/types/payloads.d.ts.map +1 -0
  123. package/types/types/transforms.d.ts +79 -0
  124. package/types/types/transforms.d.ts.map +1 -0
  125. package/types/utils/FileOfflineStorageStrategy.node.d.ts +10 -9
  126. package/types/utils/FileOfflineStorageStrategy.node.d.ts.map +1 -0
  127. package/types/utils/FileStorageStrategy.node.d.ts +9 -20
  128. package/types/utils/FileStorageStrategy.node.d.ts.map +1 -0
  129. package/types/utils/MultiServerFileStorageStrategy.node.d.ts +13 -18
  130. package/types/utils/MultiServerFileStorageStrategy.node.d.ts.map +1 -0
  131. package/types/utils/MultiServerTokenStorageStrategy.d.ts +30 -51
  132. package/types/utils/MultiServerTokenStorageStrategy.d.ts.map +1 -0
  133. package/types/utils/OfflineClientManager.d.ts +52 -88
  134. package/types/utils/OfflineClientManager.d.ts.map +1 -0
  135. package/types/utils/OfflineQueueStorageStrategy.d.ts +12 -9
  136. package/types/utils/OfflineQueueStorageStrategy.d.ts.map +1 -0
  137. package/types/utils/TokenStorage.d.ts +20 -70
  138. package/types/utils/TokenStorage.d.ts.map +1 -0
  139. package/types/utils/compat.d.ts +4 -0
  140. package/types/utils/compat.d.ts.map +1 -0
  141. package/types/utils/createDefaultMultiServerTokenStorageStrategy.d.ts +2 -11
  142. package/types/utils/createDefaultMultiServerTokenStorageStrategy.d.ts.map +1 -0
  143. package/types/utils/createDefaultOfflineStrategy.d.ts +2 -3
  144. package/types/utils/createDefaultOfflineStrategy.d.ts.map +1 -0
  145. package/types/utils/createDefaultTokenStorageStrategy.d.ts +2 -12
  146. package/types/utils/createDefaultTokenStorageStrategy.d.ts.map +1 -0
  147. package/types/utils/reactive.d.ts +10 -16
  148. package/types/utils/reactive.d.ts.map +1 -0
  149. package/types/utils/stream-utils.node.d.ts +3 -2
  150. package/types/utils/stream-utils.node.d.ts.map +1 -0
  151. package/dist/123.cocolight-api-client.browser.js +0 -1
  152. package/dist/123.cocolight-api-client.cjs +0 -1
  153. package/dist/22.cocolight-api-client.mjs.js +0 -1
  154. package/dist/339.cocolight-api-client.mjs.js +0 -1
  155. package/dist/394.cocolight-api-client.browser.js +0 -1
  156. package/dist/394.cocolight-api-client.cjs +0 -1
  157. package/dist/405.cocolight-api-client.browser.js +0 -1
  158. package/dist/405.cocolight-api-client.cjs +0 -1
  159. package/dist/774.cocolight-api-client.mjs.js +0 -1
  160. package/dist/790.cocolight-api-client.mjs.js +0 -1
  161. package/dist/931.cocolight-api-client.browser.js +0 -1
  162. package/dist/931.cocolight-api-client.cjs +0 -1
  163. package/src/EJSONType.js +0 -53
  164. package/src/api/BaseEntity.js +0 -2828
  165. package/src/api/EntityRegistry.js +0 -152
  166. package/src/api/Event.js +0 -226
  167. package/src/api/News.js +0 -244
  168. package/src/api/UserApi.js +0 -81
  169. package/src/endpoints.module.js +0 -5
  170. package/src/error.js +0 -121
  171. package/src/index.js +0 -97
  172. package/src/mixin/UserMixin.js +0 -8
  173. package/src/utils/MultiServerFileStorageStrategy.node.js +0 -87
  174. package/src/utils/MultiServerTokenStorageStrategy.js +0 -188
  175. package/src/utils/OfflineQueueStorageStrategy.js +0 -51
  176. package/src/utils/TokenStorage.js +0 -153
  177. package/src/utils/createDefaultMultiServerTokenStorageStrategy.js +0 -51
  178. package/src/utils/createDefaultTokenStorageStrategy.js +0 -49
  179. package/src/utils/stream-utils.node.js +0 -10
@@ -1,152 +0,0 @@
1
- export const EntityRegistry = new Map();
2
-
3
- /**
4
- * Enregistre une entité dans la registry.
5
- * @param {string} tag - ex: "User", "Organization"
6
- * @param {Function} EntityClass - la classe constructeur
7
- */
8
- export function registerEntity(tag, EntityClass) {
9
- EntityRegistry.set(tag, EntityClass);
10
- }
11
-
12
- /**
13
- * Récupère une instance depuis un JSON générique.
14
- * @param {Object} json - doit contenir __entityTag
15
- * @param {Object} parent - ApiClient ou entité parent
16
- * @param {Object} deps - dépendances (comme dans le constructeur)
17
- * @returns {BaseEntity|null}
18
- */
19
- export function fromEntityJSON(json, parent = null) {
20
- if (!json?.__entityTag) return null;
21
- if (!json.serverData?.collection) return json;
22
- const meta = _getEntityMeta(json.serverData.collection, json.__entityTag);
23
- if (!meta) return json;
24
- if (!meta?.entityClass?.fromJSON) throw new Error(`Classe inconnue ou fromJSON manquant pour ${json.__entityTag}`);
25
- return meta.entityClass.fromJSON(json, parent, meta.deps);
26
- }
27
-
28
- /**
29
- * Récupère la classe d'entité et ses dépendances à partir du type d'entité.
30
- *
31
- * @param {string} entityType - Le type d'entité.
32
- * @param {string} __entityTag - Le tag de l'entité.
33
- * @returns {Object|null} - Un objet contenant la classe d'entité et ses dépendances, ou null si le type d'entité n'est pas trouvé.
34
- */
35
- function _getEntityMeta(entityType, __entityTag) {
36
- const selfClass = EntityRegistry.get(__entityTag);
37
- const selfTag = __entityTag;
38
-
39
- const commonDeps = {
40
- EndpointApi: EntityRegistry.get("EndpointApi"),
41
- User: selfTag === "User" ? selfClass : EntityRegistry.get("User"),
42
- Organization: selfTag === "Organization" ? selfClass : EntityRegistry.get("Organization"),
43
- Project: selfTag === "Project" ? selfClass : EntityRegistry.get("Project"),
44
- Event: selfTag === "Event" ? selfClass : EntityRegistry.get("Event"),
45
- Poi: selfTag === "Poi" ? selfClass : EntityRegistry.get("Poi"),
46
- Badge: selfTag === "Badge" ? selfClass : EntityRegistry.get("Badge"),
47
- News: selfTag === "News" ? selfClass : EntityRegistry.get("News")
48
- };
49
-
50
- const map = {
51
- citoyens: { entityClass: commonDeps.User, deps: commonDeps },
52
- organizations:{ entityClass: commonDeps.Organization, deps: commonDeps },
53
- projects: { entityClass: commonDeps.Project, deps: commonDeps },
54
- events: { entityClass: commonDeps.Event, deps: { ...commonDeps, Badge: undefined } },
55
- poi: { entityClass: commonDeps.Poi, deps: { ...commonDeps, Badge: undefined, News: undefined } },
56
- news: { entityClass: commonDeps.News, deps: { ...commonDeps } },
57
- badges: { entityClass: commonDeps.Badge, deps: {
58
- EndpointApi: commonDeps.EndpointApi,
59
- User: commonDeps.User,
60
- Organization: commonDeps.Organization,
61
- Project: commonDeps.Project
62
- } }
63
- };
64
-
65
- return map[entityType] || null;
66
- }
67
-
68
- /**
69
- * Crée une instance d'entité basée sur le seul nom de la collection.
70
- * @param {string} collection - ex: "citoyens", "projects", ...
71
- * @param {Object} parent - ApiClient ou entité parente
72
- * @returns {BaseEntity|null}
73
- */
74
- export function createFromCollection(collection, parent = null, data = {}) {
75
- const _collectionMap = {
76
- citoyens: {
77
- entityTag: "User",
78
- meta: tag => _buildMeta(tag, { remove: [] })
79
- },
80
- organizations: {
81
- entityTag: "Organization",
82
- meta: tag => _buildMeta(tag, { remove: [] })
83
- },
84
- projects: {
85
- entityTag: "Project",
86
- meta: tag => _buildMeta(tag, { remove: [] })
87
- },
88
- events: {
89
- entityTag: "Event",
90
- meta: tag => _buildMeta(tag, { remove: ["Badge"] })
91
- },
92
- poi: {
93
- entityTag: "Poi",
94
- meta: tag => _buildMeta(tag, { remove: ["Badge","News"] })
95
- },
96
- news: {
97
- entityTag: "News",
98
- meta: tag => _buildMeta(tag, { remove: [] })
99
- },
100
- badges: {
101
- entityTag: "Badge",
102
- meta: tag => _buildCustomMeta(tag)
103
- }
104
- };
105
- const entry = _collectionMap[collection];
106
- if (!entry) {
107
- console.warn(`Collection inconnue : '${collection}'`);
108
- return null;
109
- }
110
- const { entityTag, meta } = entry;
111
- const { entityClass, deps } = meta(entityTag);
112
- return new entityClass(parent, data, deps);
113
- }
114
-
115
- /**
116
- * Construit entityClass et deps pour une collection standard.
117
- * @param {string} tag
118
- * @param {{remove: string[]}} options
119
- */
120
- function _buildMeta(tag, options) {
121
- const EntityClass = EntityRegistry.get(tag);
122
- const allDeps = {
123
- EndpointApi: EntityRegistry.get("EndpointApi"),
124
- User: EntityRegistry.get("User"),
125
- Organization: EntityRegistry.get("Organization"),
126
- Project: EntityRegistry.get("Project"),
127
- Event: EntityRegistry.get("Event"),
128
- Poi: EntityRegistry.get("Poi"),
129
- Badge: EntityRegistry.get("Badge"),
130
- News: EntityRegistry.get("News")
131
- };
132
- // inject self
133
- allDeps[tag] = EntityClass;
134
- // remove undesired
135
- options.remove.forEach(dep => delete allDeps[dep]);
136
- return { entityClass: EntityClass, deps: allDeps };
137
- }
138
-
139
- /**
140
- * Cas spécifique des badges : seules certaines dépendances.
141
- */
142
- function _buildCustomMeta(tag) {
143
- const EntityClass = EntityRegistry.get(tag);
144
- const deps = {
145
- EndpointApi: EntityRegistry.get("EndpointApi"),
146
- User: EntityRegistry.get("User"),
147
- Organization: EntityRegistry.get("Organization"),
148
- Project: EntityRegistry.get("Project")
149
- };
150
- deps[tag] = EntityClass;
151
- return { entityClass: EntityClass, deps };
152
- }
package/src/api/Event.js DELETED
@@ -1,226 +0,0 @@
1
- import { ApiError } from "../error.js";
2
- import BaseEntity from "./BaseEntity.js";
3
-
4
- export class Event extends BaseEntity {
5
- static entityType = "events";
6
-
7
- static entityTag = "Event";
8
-
9
- static SCHEMA_CONSTANTS = [
10
- "ADD_EVENT",
11
- // "UPDATE_BLOCK_DESCRIPTION",
12
- // "UPDATE_BLOCK_INFO",
13
- // "UPDATE_BLOCK_SOCIAL",
14
- // "UPDATE_BLOCK_LOCALITY",
15
- "UPDATE_BLOCK_SLUG",
16
- "PROFIL_IMAGE"
17
- ];
18
-
19
- static ADD_BLOCKS = new Map([
20
- ["ADD_EVENT", "addEvent"],
21
- ["PROFIL_IMAGE", "updateImageProfil"]
22
- ]);
23
-
24
- static UPDATE_BLOCKS = new Map([
25
- // ["UPDATE_BLOCK_DESCRIPTION", "updateDescription"],
26
- // ["UPDATE_BLOCK_SOCIAL", "updateSocial"],
27
- // ["UPDATE_BLOCK_LOCALITY", "updateLocality"],
28
- // ["UPDATE_BLOCK_INFO", "updateInfo"],
29
- ["UPDATE_BLOCK_SLUG", "updateSlug"],
30
- ["PROFIL_IMAGE", "updateImageProfil"]
31
- ]);
32
-
33
- defaultFields = {
34
- typeElement: this.getEntityType()
35
- };
36
-
37
- removeFields = [
38
- "typeElement"
39
- ];
40
-
41
- transforms = {
42
- parent: (val) => {
43
- if (!val || typeof val !== "object") return null;
44
-
45
- return Object.fromEntries(
46
- Object.entries(val).map(([key, obj]) => [
47
- key,
48
- {
49
- type: obj?.type ?? null,
50
- name: obj?.name ?? null
51
- }
52
- ])
53
- );
54
- },
55
- organizer: (val) => {
56
- if (!val || typeof val !== "object") return null;
57
-
58
- return Object.fromEntries(
59
- Object.entries(val).map(([key, obj]) => [
60
- key,
61
- {
62
- type: obj?.type ?? null,
63
- name: obj?.name ?? null
64
- }
65
- ])
66
- );
67
- }
68
- };
69
-
70
- async _add(payload) {
71
- if (!this._calledFromSave) {
72
- throw new ApiError("utilisation invalide de _add, utilisez save");
73
- }
74
-
75
- payload.id = this._newId?.();
76
- if (payload.slug) delete payload.slug;
77
-
78
- for (const [constant, methodName] of Event.ADD_BLOCKS) {
79
- const blockData = this._extractChangedFieldsFromSchema(
80
- this.apiClient,
81
- constant,
82
- { ...payload, ...this.defaultFields },
83
- () => {}
84
- );
85
- if (blockData && Object.keys(blockData).length > 0) {
86
- const data = await this[methodName](blockData);
87
- if (!this.id && data?.map?.id) {
88
- this._draftData.id = data.map.id;
89
- this._draftData.slug = data.map.slug;
90
- }
91
- }
92
- }
93
- }
94
-
95
- async _update(payload) {
96
- if(!this.isAdmin()){
97
- throw new ApiError("Vous n'avez pas les droits pour modifier cet événement", 403);
98
- }
99
-
100
- if (!this._calledFromSave) {
101
- throw new ApiError("utilisation invalide de _update, utilisez save");
102
- }
103
-
104
- let hasChanged = false;
105
-
106
- const blockData = this._extractAllValidFieldsFromSchema(
107
- this.apiClient,
108
- "ADD_EVENT",
109
- { ...payload, ...this.defaultFields },
110
- () => this.initialDraftData,
111
- this.removeFields
112
- );
113
- if (blockData && Object.keys(blockData).length > 0) {
114
- await this["addEvent"](blockData);
115
- hasChanged = true;
116
- }
117
-
118
- if (payload.id) delete payload.id;
119
-
120
- for (const [constant, methodName] of Event.UPDATE_BLOCKS) {
121
- const blockData = this._extractChangedFieldsFromSchema(
122
- this.apiClient,
123
- constant,
124
- { ...payload, ...this.defaultFields },
125
- () => this.initialDraftData,
126
- this.removeFields
127
- );
128
- if (blockData && Object.keys(blockData).length > 0) {
129
- await this[methodName](blockData);
130
- hasChanged = true;
131
- }
132
- }
133
-
134
- return hasChanged;
135
- }
136
-
137
- async addEvent(data = {}) {
138
-
139
- if (!this.isMe && !data.organizer) {
140
- data.organizer = {};
141
- data.organizer[`${this.parent.id}`] = {
142
- type: this.parent.getEntityType(),
143
- name: this.parent.name
144
- };
145
- }
146
-
147
- return this.callIsConnected(() => this.endpointApi.addEvent(data));
148
- }
149
-
150
- async getOrganizations() {
151
- throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`);
152
- }
153
-
154
- async getProjects() {
155
- throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`);
156
- }
157
-
158
- async getEvents() {
159
- throw new ApiError(`getEvents - les sous-events ne sont pas encore implémentés dans ${this.constructor.name}`);
160
- }
161
-
162
- async getPois() {
163
- throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`);
164
- }
165
-
166
- async getBadgesIssuer() {
167
- throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`);
168
- }
169
-
170
- async getNews(data = {}) {
171
- return super.getNews(data);
172
- }
173
-
174
- async getSubscribers(data = {}) {
175
- return super.getSubscribers(data);
176
- }
177
-
178
- async project() {
179
- throw new ApiError(`project n'existe pas dans ${this.constructor.name}`);
180
- }
181
-
182
- async poi() {
183
- throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`);
184
- }
185
-
186
- async event() {
187
- throw new ApiError(`les sous-events ne sont pas encore implémentés dans ${this.constructor.name}`);
188
- }
189
-
190
- async badge() {
191
- throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`);
192
- }
193
-
194
- /**
195
- * Crée une instance de news et la récupère si nécessaire.
196
- *
197
- * @param {Object} newsData - Les données nécessaires pour initialiser la news.
198
- * @returns {Promise<News>} Une promesse qui résout l'objet News créé.
199
- * @throws {Error} Si une erreur se produit lors de la création de la news.
200
- */
201
- async news(newsData = {}) {
202
- return super.news(newsData);
203
- }
204
-
205
- /**
206
- * Suivre un événement.
207
- * Cette action permet à l'utilisateur de suivre un événement.
208
- *
209
- * @returns {Promise<Object>} - Résultat de l'action de suivi.
210
- * @throws {ApiError} - Si l'utilisateur n'est pas connecté ou si l'entité ne supporte pas l'action.
211
- */
212
- async follow() {
213
- return super.follow();
214
- }
215
-
216
- /**
217
- * Se désabonne d'un événement.
218
- *
219
- * @returns {Promise<Object>} - Résultat de la désinscription.
220
- * @throws {ApiError} - Si l'utilisateur n'est pas connecté ou si l'entité n'est pas enregistrée.
221
- */
222
- async unfollow() {
223
- return super.unfollow();
224
- }
225
-
226
- }
package/src/api/News.js DELETED
@@ -1,244 +0,0 @@
1
- import { ApiError } from "../error.js";
2
- import BaseEntity from "./BaseEntity.js";
3
-
4
- export class News extends BaseEntity {
5
- static entityType = "news";
6
-
7
- static entityTag = "News";
8
-
9
- static SCHEMA_CONSTANTS = [
10
- "ADD_NEWS"
11
- ];
12
-
13
- static ADD_BLOCKS = new Map([
14
- ["ADD_NEWS", "addNews"]
15
- ]);
16
-
17
- static UPDATE_BLOCKS = new Map([
18
- ["ADD_NEWS", "updateNews"]
19
- ]);
20
-
21
- defaultFields = {
22
-
23
- };
24
-
25
- removeFields = [
26
-
27
- ];
28
-
29
- transforms = {
30
- scope: val => val?.type,
31
- mentions: val =>
32
- Array.isArray(val)
33
- ? val.map(m => ({ ...m, count: parseInt(m.count) }))
34
- : [],
35
- mediaImg: val => {
36
- const images = val?.images?.map(img => img.id).filter(Boolean) || [];
37
- return images.length > 0 ? { countImages: images.length, images } : undefined;
38
- },
39
- mediaFile: val => {
40
- const files = val?.files?.map(f => f.id).filter(Boolean) || [];
41
- return files.length > 0 ? { countFiles: files.length, files } : undefined;
42
- }
43
- };
44
-
45
- /**
46
- * Récupérer des actualités par IDs : Récupère des actualités à partir d’une liste d’identifiants.
47
- * Constant : GET_NEWS_BY_ID
48
- */
49
- async get() {
50
- if (!this.id) throw new ApiError("Impossible de rafraîchir sans ID.");
51
-
52
- const newsArray = await this.callIsConnected(() =>
53
- this.endpointApi.getNewsById({ ids: [this.id] })
54
- );
55
-
56
- if (newsArray && Array.isArray(newsArray) && newsArray.length === 1) {
57
- const data = newsArray[0];
58
- this._setData(data);
59
- return this.serverData;
60
- }
61
- throw new ApiError(`Aucune actualité trouvée pour l'ID ${this.id}`);
62
- }
63
-
64
-
65
- async _add(payload) {
66
- if (!this._calledFromSave) {
67
- throw new Error("utilisation invalide de _add, utilisez save");
68
- }
69
-
70
- // si le texte est vide, on met un espace pour que le champ soit pris en compte car sur le serveur
71
- // il y a une vérification de la taille du texte je pense
72
- if(payload.text === ""){
73
- payload.text = " ";
74
- }
75
- payload.parentId = this.parent.id;
76
- payload.parentType = this.parent.getEntityType();
77
-
78
- // const data = await this.callIsConnected(() => this.endpointApi.addNews(payload));
79
- // this._draftData.id = data.object.id;
80
- // // TODO : voir si j'ai ce qui faut dans reponseData de ADD_NEWS pour mettre à jour #serverData
81
- // // c'est dans reponseData.object
82
- // // if(data?.object){
83
- // // this._serverData = { ...data.object };
84
- // // }
85
-
86
- for (const [constant, methodName] of News.ADD_BLOCKS) {
87
- const blockData = this._extractChangedFieldsFromSchema(
88
- this.apiClient,
89
- constant,
90
- { ...payload, ...this.defaultFields },
91
- () => {}
92
- );
93
- if (blockData && Object.keys(blockData).length > 0) {
94
- const data = await this[methodName](blockData);
95
- if (!this.id && data?.object?.id) {
96
- this._draftData.id = data.object.id;
97
- // this._serverData = { ...data.object };
98
- }
99
- }
100
- }
101
- }
102
-
103
- async _update(payload) {
104
- if (!this._calledFromSave) {
105
- throw new Error("utilisation invalide de _update, utilisez save");
106
- }
107
-
108
- if (payload.id) delete payload.id;
109
-
110
- // si le texte est vide, on met un espace pour que le champ soit pris en compte car sur le serveur
111
- // il y a une vérification de la taille du texte je pense
112
- if(payload?.text === ""){
113
- payload.text = " ";
114
- }
115
-
116
- payload.parentId = this.parent.id;
117
- payload.parentType = this.parent.getEntityType();
118
- payload.idNews = this.id;
119
-
120
- let hasChanged = false;
121
- const data = await this.callIsConnected(() => this.endpointApi.updateNews(payload));
122
- // TODO : voir si j'ai ce qui faut dans data de UPDATE_NEWS pour mettre à jour #serverData
123
- // c'est dans data.object
124
- if(data?.object){
125
- this._serverData = { ...data.object };
126
- }
127
- hasChanged = true;
128
- return hasChanged;
129
-
130
- // if (payload.id) delete payload.id;
131
- // let hasChanged = false;
132
-
133
- // for (const [constant, methodName] of News.UPDATE_BLOCKS) {
134
- // const blockData = this._extractChangedFieldsFromSchema(
135
- // this.apiClient,
136
- // constant,
137
- // { ...payload, ...this.defaultFields },
138
- // () => this.initialDraftData,
139
- // this.removeFields
140
- // );
141
- // if (blockData && Object.keys(blockData).length > 0) {
142
- // await this[methodName](blockData);
143
- // hasChanged = true;
144
- // }
145
- // }
146
-
147
- // return hasChanged;
148
- }
149
-
150
- async addNews(data = {}) {
151
- return this.callIsConnected(() => this.endpointApi.addNews(data));
152
- }
153
-
154
- async updateNews(data = {}) {
155
- return this.callIsConnected(() => this.endpointApi.updateNews(data));
156
- }
157
-
158
- async addMention({ slug, id }) {
159
- try {
160
- if (!slug && !id) {
161
- throw new ApiError("Vous devez fournir un slug ou un id pour ajouter une mention.");
162
- }
163
-
164
- const userInstance = await this.entity("citoyens", { id, slug });
165
- // const userInstance = new this.deps.User(this.apiClient, { id, slug }, { EndpointApi: this.endpointApi });
166
- const user = userInstance.serverData;
167
-
168
- if (!this._draftData.mentions) {
169
- this._draftData.mentions = [];
170
- }
171
- // Vérification si la mention existe déjà
172
- if (this._draftData.mentions.find((mention) => mention.id === user.id)) {
173
- // Si la mention existe déjà, on incrémente le compteur
174
- this._draftData.mentions = this._draftData.mentions.map((mention) => {
175
- if (mention.id === user.id) {
176
- mention.count += 1;
177
- }
178
- return mention;
179
- });
180
- return this._draftData.mentions;
181
- }
182
- const mention = { id: user.id, slug: user.slug, type: userInstance.getEntityType(), name: user.name, value: user.name, count: 1 };
183
- this._draftData.mentions.push(mention);
184
- return this._draftData.mentions;
185
- } catch (error) {
186
- this.apiClient._logger.error("Erreur lors de l'ajout de la mention :", error);
187
- throw error;
188
- }
189
-
190
- }
191
-
192
-
193
- /**
194
- * Ajouter une image à une actualité : Ajoute une images à une actualité.
195
- * Constant : ADD_IMAGE_NEWS
196
- */
197
- async addImage(image) {
198
- image = await this._validateImage(image);
199
- const data = { pathParams: { folder: this.parent.getEntityType(), ownerId: this.parent.id }, newsImage: image };
200
- const dataImage = await this.callIsConnected(() => this.endpointApi.addImageNews(data));
201
- if (this._draftData.mediaImg) {
202
- this._draftData.mediaImg.countImages = this._draftData.mediaImg.countImages + 1;
203
- this._draftData.mediaImg.images.push(dataImage.id);
204
- } else {
205
- this._draftData.mediaImg = { countImages: 1, images: [dataImage.id] };
206
- }
207
- return dataImage;
208
- }
209
-
210
- /**
211
- * Ajouter un fichier à une actualité : Ajoute un fichier à une actualité.
212
- * Constant : ADD_FILE_NEWS
213
- */
214
- async addFile(file) {
215
- file = await this._validateFile(file);
216
- const data = { pathParams: { folder: this.parent.getEntityType(), ownerId: this.parent.id }, newsFile: file };
217
- const dataFile = await this.callIsConnected(() =>this.endpointApi.addFileNews(data));
218
- if (this._draftData.mediaFile) {
219
- this._draftData.mediaFile.countFiles = this._draftData.mediaFile.countFiles + 1;
220
- this._draftData.mediaFile.files.push(dataFile);
221
- } else {
222
- this._draftData.mediaFile = { countFiles: 1, files: [dataFile] };
223
- }
224
- return dataFile;
225
- }
226
-
227
- /**
228
- * Supprimer une actualité : Supprime une actualité existante.
229
- * Constant : DELETE_NEWS
230
- */
231
- async delete() {
232
- if(!this.id) {
233
- throw new ApiError("Vous devez fournir un id pour supprimer une news.");
234
- }
235
- const data = { pathParams: { id: this.id } };
236
- await this.callIsConnected(() => this.endpointApi.deleteNews(data));
237
- this._draftData = {};
238
- this._serverData = null;
239
- this._draftData.id = null;
240
- this._isDeleted = true;
241
- }
242
-
243
-
244
- }
@@ -1,81 +0,0 @@
1
- // UserApi.js
2
- import ApiClient from "../ApiClient.js";
3
- import { ApiError, ApiResponseError } from "../error.js";
4
- import { Badge } from "./Badge.js";
5
- import EndpointApi from "./EndpointApi.js";
6
- import { Event } from "./Event.js";
7
- import { News } from "./News.js";
8
- import { Organization } from "./Organization.js";
9
- import { Poi } from "./Poi.js";
10
- import { Project } from "./Project.js";
11
- import { User } from "./User.js";
12
-
13
- export class UserApi {
14
-
15
- constructor(clientOrOptions) {
16
- if (clientOrOptions instanceof ApiClient) {
17
- this.client = clientOrOptions;
18
- } else {
19
- // Injection de dépendance : ApiClient est créé à partir des options
20
- this.client = new ApiClient(clientOrOptions);
21
- // si l'option "tokenStorageStrategy" est définie, on l'utilise pour créer une instance de ApiClient
22
- }
23
-
24
- this.loggedUser = null;
25
- }
26
-
27
- get isConnected() {
28
- return this.client.isConnected;
29
- }
30
- get userId() {
31
- return this.client.userId;
32
- }
33
-
34
- // Méthode d'authentification : récupère les données utilisateur depuis un endpoint
35
- async login(email, password) {
36
- return this.client.safeCall(async () => {
37
- // Appel à un endpoint d'authentification
38
- const response = await this.client.callEndpoint("AUTHENTICATE_URL", { email, password });
39
- // Création d'une instance de LoggedInUser à partir des données reçues
40
- this.loggedUser = new User(this.client, response.data.user, { EndpointApi, Organization, Project, Event, Poi, Badge, News });
41
- return this.loggedUser;
42
- });
43
- }
44
-
45
- async meIsconnected() {
46
- if(!this.client.isConnected || !this.client.userId) {
47
- throw new ApiError("User not connected", 401);
48
- }
49
- this.client._logger.info("UserApi", "meIsconnected", this.client.userId);
50
- this.loggedUser = new User(this.client, { id: this.client.userId }, { EndpointApi, Organization, Project, Event, Poi, Badge, News });
51
- return this.loggedUser;
52
- }
53
-
54
-
55
- async register({
56
- name,
57
- username,
58
- email,
59
- pwd,
60
- } = {}) {
61
- return this.client.safeCall(async () => {
62
- const response = await this.client.callEndpoint("PERSON_REGISTER", { name, username, email, pwd });
63
- if(response?.data?.result === false) {
64
- throw new ApiResponseError(response.data.msg, response.status, response.data);
65
- }
66
- return response.data;
67
- });
68
- }
69
-
70
-
71
- async recoverPassword(email) {
72
- return this.client.safeCall(async () => {
73
- const response = await this.client.callEndpoint("PASSWORD_RECOVERY", { email });
74
- if(response?.data?.result === false) {
75
- throw new ApiResponseError(response.data.msg, response.status, response.data);
76
- }
77
- return response.data;
78
- });
79
- }
80
-
81
- }