@communecter/cocolight-api-client 1.0.19 → 1.0.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@communecter/cocolight-api-client",
3
- "version": "1.0.19",
3
+ "version": "1.0.20",
4
4
  "description": "Client Axios simplifié pour l'API cocolight",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,7 +15,7 @@ export class BaseEntity {
15
15
  this.__entityTag = config.entityTag || this.constructor.name || "BaseEntity";
16
16
  this.deps = deps;
17
17
 
18
- this.EndpointApiClass = deps.EndpointApi;
18
+ // this.EndpointApiClass = deps.EndpointApi;
19
19
 
20
20
  if (parent?.__entityTag === "ApiClient") {
21
21
  this.apiClient = parent;
@@ -27,9 +27,18 @@ export class BaseEntity {
27
27
  throw new ApiError("Parent invalide ou ApiClient manquant.");
28
28
  }
29
29
 
30
- this.endpointApi = typeof deps.EndpointApi === "function"
31
- ? new deps.EndpointApi(this.apiClient)
32
- : deps.EndpointApi;
30
+ // this.endpointApi = typeof deps.EndpointApi === "function"
31
+ // ? new deps.EndpointApi(this.apiClient)
32
+ // : deps.EndpointApi;
33
+
34
+ // Gérer les deux cas : fonction constructeur ou instance
35
+ if (typeof deps.EndpointApi === "function") {
36
+ this.endpointApi = new deps.EndpointApi(this.apiClient);
37
+ } else if (typeof deps.EndpointApi === "object") {
38
+ this.endpointApi = deps.EndpointApi;
39
+ } else {
40
+ throw new ApiError("deps.EndpointApi doit être une classe ou une instance valide.");
41
+ }
33
42
 
34
43
  this._serverData = null;
35
44
 
package/src/api/User.js CHANGED
@@ -1,15 +1,9 @@
1
1
  import { ApiError, ApiResponseError } from "../error.js";
2
- import { DraftStateMixin } from "../mixin/DraftStateMixin.js";
3
- import { MutualEntityMixin } from "../mixin/MutualEntityMixin.js";
2
+ import BaseEntity from "./BaseEntity.js";
4
3
  import { UserMixin } from "../mixin/UserMixin.js";
5
- import { UtilMixin } from "../mixin/UtilMixin.js";
6
4
 
7
5
  // User.js
8
- export class User {
9
- _draftData = {};
10
- _initialDraftData = {};
11
- _serverData = null;
12
- _calledFromSave = false;
6
+ export class User extends BaseEntity {
13
7
 
14
8
  static entityType = "citoyens";
15
9
 
@@ -31,6 +25,41 @@ export class User {
31
25
  ["PROFIL_IMAGE", "updateImageProfil"]
32
26
  ]);
33
27
 
28
+ /**
29
+ * Champs par défaut pour les schemas json ou l'on extrait les fields. (pour les if/else/then)
30
+ *
31
+ * @property {Object} defaultFields - Un objet contenant les propriétés par défaut pour l'entité User.
32
+ */
33
+ defaultFields = {
34
+ typeElement: this.getEntityType(),
35
+ };
36
+
37
+ /**
38
+ * Champs à supprimer de draft lors de la construction du proxy.
39
+ *
40
+ * @property {Array<string>} removeFields - Un tableau de chaînes représentant les champs à supprimer.
41
+ */
42
+ removeFields = [
43
+ "typeElement",
44
+ ];
45
+
46
+ /**
47
+ * Transformateurs appliqués lors de la lecture du draft.
48
+ *
49
+ * @type {Object<string, function>}
50
+ */
51
+ transforms = {
52
+ github: (val, full) => full?.socialNetwork?.github,
53
+ gitlab: (val, full) => full?.socialNetwork?.gitlab,
54
+ facebook: (val, full) => full?.socialNetwork?.facebook,
55
+ twitter: (val, full) => full?.socialNetwork?.twitter,
56
+ instagram: (val, full) => full?.socialNetwork?.instagram,
57
+ diaspora: (val, full) => full?.socialNetwork?.diaspora,
58
+ mastodon: (val, full) => full?.socialNetwork?.mastodon,
59
+ telegram: (val, full) => full?.socialNetwork?.telegram,
60
+ signal: (val, full) => full?.socialNetwork?.signal
61
+ };
62
+
34
63
  /**
35
64
  * Crée une instance de User.
36
65
  *
@@ -51,120 +80,33 @@ export class User {
51
80
  */
52
81
 
53
82
  constructor(parent, data = {}, deps = {}) {
54
- this.__entityTag = "User";
55
-
56
83
  if(!deps.EndpointApi){
57
84
  throw new ApiError("EndpointApi class must be injected to avoid circular dependency.");
58
85
  }
59
86
  if (!data?.id && !data?.slug) {
60
87
  throw new ApiError("Vous devez fournir un id ou un slug pour créer un User.");
61
88
  }
62
-
89
+
63
90
  if (!deps.Organization) throw new ApiError("Organization class must be injected.");
64
91
  if (!deps.Project) throw new ApiError("Project class must be injected.");
65
92
  if (!deps.Event) throw new ApiError("Event class must be injected.");
66
93
  if (!deps.Poi) throw new ApiError("Poi class must be injected.");
67
94
  if (!deps.Badge) throw new ApiError("Badge class must be injected.");
68
95
  if (!deps.News) throw new ApiError("News class must be injected.");
96
+
97
+ super(parent, data, deps);
69
98
 
70
- if (parent?.__entityTag === "ApiClient") {
71
- this.apiClient = parent;
72
- this.parent = null;
73
- } else if (parent?.apiClient) {
74
- this.apiClient = parent.apiClient;
75
- this.parent = parent;
76
- } else {
77
- throw new ApiError("Parent invalide ou ApiClient manquant.");
78
- }
79
-
80
- this.deps = deps;
81
-
82
- // Gérer les deux cas : fonction constructeur ou instance
83
- if (typeof deps.EndpointApi === "function") {
84
- this.endpointApi = new deps.EndpointApi(this.apiClient);
85
- } else if (typeof deps.EndpointApi === "object") {
86
- this.endpointApi = deps.EndpointApi;
87
- } else {
88
- throw new ApiError("deps.EndpointApi doit être une classe ou une instance valide.");
89
- }
90
-
91
- this._serverData = null;
92
-
93
- const { draft, proxy } = this._buildDraftAndProxy({
94
- data: { ...data, ...this.defaultFields },
95
- serverData: this._serverData,
96
- constant: User.SCHEMA_CONSTANTS,
97
- apiClient: this.apiClient,
98
- transforms: this.transforms,
99
- removeFields: this.removeFields
100
- });
101
-
102
- this._initialDraftData = JSON.parse(JSON.stringify(draft)); // snapshot propre
103
- this._draftData = draft;
104
- this.data = proxy;
105
- }
106
-
107
- get id() {
108
- return this._draftData.id || null;
109
- }
110
-
111
- _id(newId) {
112
- this._draftData.id = newId;
99
+ // this.__entityTag = "User";
113
100
  }
114
101
 
115
102
  get slug() {
116
103
  return this._draftData.slug || null;
117
104
  }
118
105
 
119
- get isConnected() {
120
- return this.apiClient.isConnected;
121
- }
122
-
123
- _setData(newData) {
124
- this._serverData = { ...newData };
125
-
126
- const { draft, proxy } = this._buildDraftAndProxy({
127
- data: { ...newData, ...this.defaultFields },
128
- serverData: this._serverData,
129
- constant: User.SCHEMA_CONSTANTS,
130
- apiClient: this.apiClient,
131
- transforms: this.transforms,
132
- removeFields: this.removeFields
133
- });
134
- this._initialDraftData = JSON.parse(JSON.stringify(draft));
135
- this._draftData = draft;
136
- this.data = proxy;
137
- }
138
-
139
- getEntityType() {
140
- return User.entityType;
141
- }
142
-
143
- get userId() {
144
- return this.apiClient.userId;
145
- }
146
-
147
106
  get isMe() {
148
107
  return this.isConnected && this.userId === this.id;
149
108
  }
150
109
 
151
- get draftData() {
152
- return this._draftData;
153
- }
154
-
155
- get initialDraftData() {
156
- return this._initialDraftData;
157
- }
158
-
159
- get serverData() {
160
- return this._serverData;
161
- }
162
-
163
- async refresh() {
164
- if (!this.id) throw new ApiError("Impossible de rafraîchir sans ID.");
165
- return this.get();
166
- }
167
-
168
110
  /**
169
111
  * Récupère le profil complet de l'utilisateur.
170
112
  * Si l'utilisateur est connecté, on appelle le endpoint ME_INFO_URL,
@@ -210,26 +152,14 @@ export class User {
210
152
  * @throws {ApiError} - Si l'utilisateur n'est pas autorisé.
211
153
  */
212
154
  async save() {
213
-
214
155
  if(!this.isMe){
215
156
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour sauvegarder.");
216
157
  }
217
- this._calledFromSave = true;
218
- try{
219
- const payload = { ...this._draftData };
220
-
221
- if (this.id) {
222
- const hasChanged = await this._update(payload);
223
- if (hasChanged) {
224
- // this._updateInitialDraftSnapshot();
225
- await this.refresh();
226
- }
227
- return this._serverData;
228
- }
229
- } finally {
230
- this._calledFromSave = false;
231
- }
232
-
158
+ await super.save();
159
+ }
160
+
161
+ async _add() {
162
+ throw new ApiError("Vous ne pouvez pas ajouter un utilisateur par ce moyen.");
233
163
  }
234
164
 
235
165
  /**
@@ -296,7 +226,10 @@ export class User {
296
226
  * @returns {Promise<void>} - Résultat de la mise à jour.
297
227
  */
298
228
  async updateSettings(data = {}) {
299
- await this.callIsMe(() => this.endpointApi.updateSettings(data));
229
+ if(!this.isMe){
230
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les paramètres.");
231
+ }
232
+ await super.updateSettings(data);
300
233
  await this.refresh();
301
234
  }
302
235
 
@@ -305,7 +238,10 @@ export class User {
305
238
  * Constant : UPDATE_BLOCK_DESCRIPTION
306
239
  */
307
240
  async updateDescription(data = {}) {
308
- return this.callIsMe(() => this.endpointApi.updateBlockDescription(data));
241
+ if(!this.isMe){
242
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour la description.");
243
+ }
244
+ return super.updateDescription(data);
309
245
  }
310
246
 
311
247
  /**
@@ -313,7 +249,10 @@ export class User {
313
249
  * Constant : UPDATE_BLOCK_INFO
314
250
  */
315
251
  async updateInfo(data = {}) {
316
- return this.callIsMe(() => this.endpointApi.updateBlockInfo(data));
252
+ if(!this.isMe){
253
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les informations.");
254
+ }
255
+ return super.updateInfo(data);
317
256
  }
318
257
 
319
258
  /**
@@ -321,7 +260,10 @@ export class User {
321
260
  * Constant : UPDATE_BLOCK_SOCIAL
322
261
  */
323
262
  async updateSocial(data = {}) {
324
- return this.callIsMe(() => this.endpointApi.updateBlockSocial(data));
263
+ if(!this.isMe){
264
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les réseaux sociaux.");
265
+ }
266
+ return super.updateSocial(data);
325
267
  }
326
268
 
327
269
  /**
@@ -329,7 +271,10 @@ export class User {
329
271
  * Constant : UPDATE_BLOCK_LOCALITY
330
272
  */
331
273
  async updateLocality(data = {}) {
332
- return this.callIsMe(() => this.endpointApi.updateBlockLocality(data));
274
+ if(!this.isMe){
275
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour la localité.");
276
+ }
277
+ return super.updateLocality(data);
333
278
  }
334
279
 
335
280
  /**
@@ -337,15 +282,10 @@ export class User {
337
282
  * Constant : UPDATE_BLOCK_SLUG
338
283
  */
339
284
  async updateSlug({ slug }) {
340
- try {
341
- await this.endpointApi.check({ slug });
342
- } catch (error) {
343
- if(error instanceof ApiResponseError) {
344
- throw new ApiResponseError("Erreur lors de la vérification du slug.", error.status, error.data);
345
- }
346
- throw error;
285
+ if(!this.isMe){
286
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour le slug.");
347
287
  }
348
- return this.callIsMe(() => this.endpointApi.updateBlockSlug({ slug }));
288
+ return super.updateSlug({ slug });
349
289
  }
350
290
 
351
291
  /**
@@ -353,8 +293,10 @@ export class User {
353
293
  * Constant : PROFIL_IMAGE
354
294
  */
355
295
  async updateImageProfil({ profil_avatar: image }) {
356
- image = await this._validateImage(image);
357
- return this.callIsMe(() => this.endpointApi.profilImage({ profil_avatar: image }));
296
+ if(!this.isMe){
297
+ throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour l'image de profil.");
298
+ }
299
+ return super.updateImageProfil({ profil_avatar: image });
358
300
  }
359
301
 
360
302
  /**
@@ -404,37 +346,7 @@ export class User {
404
346
  * Constant : GET_PROJECTS_ADMIN | GET_PROJECTS_NO_ADMIN
405
347
  */
406
348
  async getProjects(data = {}) {
407
- delete data?.pathParams;
408
-
409
- const fetchFn = this.isMe
410
- ? () => this.callIsMe(() => this.endpointApi.getProjectsAdmin(data))
411
- : () => this.endpointApi.getProjectsNoAdmin(data);
412
-
413
- if (!this.isMe && !data.filters) {
414
- data.filters = {
415
- "$or": {
416
- [`links.contributors.${this.id}`]: { "$exists": true },
417
- [`parent.${this.id}`]: { "$exists": true }
418
- },
419
- [`links.contributors.${this.id}`]: { "$exists": true }
420
- // TODO : revoir les filtres pour harmoniser avec orga (schema pris de cocolight)
421
- };
422
- }
423
-
424
- const arrayObjetProjects = await fetchFn();
425
-
426
- if (!Array.isArray(arrayObjetProjects.results)) {
427
- throw new ApiResponseError("Erreur lors de la récupération des projets.", 500, arrayObjetProjects.results);
428
- }
429
-
430
- const rawProjectsList = arrayObjetProjects.results.map(
431
- (d) => this.linkEntity?.(d.collection, d) ?? d
432
- );
433
-
434
- return {
435
- count: arrayObjetProjects?.count?.projects ?? 0,
436
- results: rawProjectsList
437
- };
349
+ return super.getProjects(data);
438
350
  }
439
351
 
440
352
  /**
@@ -442,33 +354,7 @@ export class User {
442
354
  * Constant : GET_POIS_NO_ADMIN / GET_POIS_ADMIN
443
355
  */
444
356
  async getPois(data = {}) {
445
- delete data?.pathParams;
446
-
447
- const fetchFn = this.isMe
448
- ? () => this.callIsMe(() => this.endpointApi.getPoisAdmin(data))
449
- : () => this.endpointApi.getPoisNoAdmin(data);
450
-
451
-
452
- if (!this.isMe && !data.filters) {
453
- data.filters = {
454
- [`parent.${this.id}`]: { "$exists": true },
455
- };
456
- }
457
-
458
- const arrayObjetPois = await fetchFn();
459
- if (!Array.isArray(arrayObjetPois.results)) {
460
- throw new ApiResponseError("Erreur lors de la récupération des POIs.", 500, arrayObjetPois.results);
461
- }
462
-
463
- // lier les entités au objets
464
- const rawPoisList = arrayObjetPois.results.map(
465
- (d) => this.linkEntity?.(d.collection, d) ?? d
466
- );
467
-
468
- return {
469
- count: arrayObjetPois.count?.poi ?? 0,
470
- results: rawPoisList
471
- };
357
+ return super.getPois(data);
472
358
  }
473
359
 
474
360
  /**
@@ -476,23 +362,7 @@ export class User {
476
362
  * Constant : GET_NEWS
477
363
  */
478
364
  async getNews(data = {}) {
479
- if (data.pathParams) {
480
- delete data.pathParams;
481
- }
482
- if (!this.isMe){
483
- // is not me add id
484
- data.pathParams = { id: this.id };
485
- }
486
- const arrayObjetNews = await this.endpointApi.getNews(data);
487
- if(!Array.isArray(arrayObjetNews)){
488
- throw new ApiResponseError("Erreur lors de la récupération des actualités.", 500, arrayObjetNews);
489
- }
490
-
491
- const rawNewsList = arrayObjetNews.map(
492
- (d) => this.linkEntity?.(d.collection, d) ?? d
493
- );
494
-
495
- return this._createFilteredProxy(rawNewsList);
365
+ return super.getNews(data);
496
366
  }
497
367
 
498
368
  /**
@@ -563,28 +433,7 @@ export class User {
563
433
  * Constant : GET_SUBSCRIBERS
564
434
  */
565
435
  async getSubscribers(data = {}) {
566
- delete data?.pathParams;
567
-
568
- if (!this.isMe && !data.filters) {
569
- data.filters = {
570
- [`links.follows.${this.id}`]: { "$exists": true },
571
- };
572
- }
573
-
574
- const arrayObjetSubscribers = await this.endpointApi.getSubscribers(data);
575
- if (!Array.isArray(arrayObjetSubscribers.results)) {
576
- throw new ApiResponseError("Erreur lors de la récupération des abonnés.", 500, arrayObjetSubscribers.results);
577
- }
578
-
579
- // lier les entités au objets
580
- const rawSubscribersList = arrayObjetSubscribers.results.map(
581
- (d) => this.linkEntity?.(d.collection, d) ?? d
582
- );
583
-
584
- return {
585
- count: arrayObjetSubscribers.count,
586
- results: rawSubscribersList
587
- };
436
+ return super.getSubscribers(data);
588
437
  }
589
438
 
590
439
  /**
@@ -598,26 +447,7 @@ export class User {
598
447
  * Constant : GET_BADGES
599
448
  */
600
449
  async getBadgesIssuer(data = {}) {
601
- delete data?.pathParams;
602
-
603
- data.filters = data.filters || {};
604
- data.filters["$or"] = {};
605
- data.filters["$or"][`issuer.${this.id}`] = { "$exists": true };
606
-
607
- const arrayObjetBadges = await this.endpointApi.getBadges(data);
608
- if (!Array.isArray(arrayObjetBadges.results)) {
609
- throw new ApiResponseError("Erreur lors de la récupération des badges.", 500, arrayObjetBadges.results);
610
- }
611
-
612
- // lier les entités au objets
613
- const rawBadgesList = arrayObjetBadges.results.map(
614
- (d) => this.linkEntity?.(d.collection, d) ?? d
615
- );
616
-
617
- return {
618
- count: arrayObjetBadges.count?.badges ?? 0,
619
- results: rawBadgesList
620
- };
450
+ return super.getBadgesIssuer(data);
621
451
  }
622
452
 
623
453
  /**
@@ -655,7 +485,7 @@ export class User {
655
485
  if(!this.isMe){
656
486
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une organisation.");
657
487
  }
658
- return this.entity("organizations", organizationData);
488
+ return super.organization(organizationData);
659
489
  }
660
490
 
661
491
  /**
@@ -669,7 +499,7 @@ export class User {
669
499
  if(!this.isMe){
670
500
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un projet.");
671
501
  }
672
- return this.entity("projects", projectData);
502
+ return super.project(projectData);
673
503
  }
674
504
 
675
505
  /**
@@ -683,7 +513,7 @@ export class User {
683
513
  if(!this.isMe){
684
514
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une actualité.");
685
515
  }
686
- return this.entity("news", newsData);
516
+ return super.news(newsData);
687
517
  }
688
518
 
689
519
  /**
@@ -697,7 +527,7 @@ export class User {
697
527
  if(!this.isMe){
698
528
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un POI.");
699
529
  }
700
- return this.entity("poi", poiData);
530
+ return super.poi(poiData);
701
531
  }
702
532
 
703
533
  /**
@@ -711,7 +541,7 @@ export class User {
711
541
  if(!this.isMe){
712
542
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un événement.");
713
543
  }
714
- return this.entity("events", eventData);
544
+ return super.event(eventData);
715
545
  }
716
546
 
717
547
  /**
@@ -725,54 +555,11 @@ export class User {
725
555
  if(!this.isMe){
726
556
  throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un badge.");
727
557
  }
728
- return this.entity("badges", badgeData);
729
- }
730
-
731
- _updateInitialDraftSnapshot() {
732
- this._initialDraftData = JSON.parse(JSON.stringify(this._draftData));
558
+ return super.badge(badgeData);
733
559
  }
734
560
 
735
- // TODO: ne fonctionne pas
736
- hasChanges() {
737
- return JSON.stringify(this._draftData) !== JSON.stringify(this._initialDraftData);
738
- }
739
-
740
- /**
741
- * Champs par défaut pour les schemas json ou l'on extrait les fields. (pour les if/else/then)
742
- *
743
- * @property {Object} defaultFields - Un objet contenant les propriétés par défaut pour l'entité User.
744
- */
745
- defaultFields = {
746
- typeElement: this.getEntityType(),
747
- };
748
-
749
- /**
750
- * Champs à supprimer de draft lors de la construction du proxy.
751
- *
752
- * @property {Array<string>} removeFields - Un tableau de chaînes représentant les champs à supprimer.
753
- */
754
- removeFields = [
755
- "typeElement",
756
- ];
757
-
758
- /**
759
- * Transformateurs appliqués lors de la lecture du draft.
760
- *
761
- * @type {Object<string, function>}
762
- */
763
- transforms = {
764
- github: (val, full) => full?.socialNetwork?.github,
765
- gitlab: (val, full) => full?.socialNetwork?.gitlab,
766
- facebook: (val, full) => full?.socialNetwork?.facebook,
767
- twitter: (val, full) => full?.socialNetwork?.twitter,
768
- instagram: (val, full) => full?.socialNetwork?.instagram,
769
- diaspora: (val, full) => full?.socialNetwork?.diaspora,
770
- mastodon: (val, full) => full?.socialNetwork?.mastodon,
771
- telegram: (val, full) => full?.socialNetwork?.telegram,
772
- signal: (val, full) => full?.socialNetwork?.signal
773
- };
774
561
  }
775
562
 
776
563
  // Incorporation des mixins dans User
777
- Object.assign(User.prototype, MutualEntityMixin, UtilMixin, UserMixin, DraftStateMixin);
564
+ Object.assign(User.prototype, UserMixin);
778
565