@communecter/cocolight-api-client 1.0.6 → 1.0.8
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 +4 -4
- package/dist/cocolight-api-client.browser.js +7 -6
- package/dist/cocolight-api-client.browser.js.LICENSE.txt +1 -0
- package/dist/cocolight-api-client.cjs +2 -1
- package/dist/cocolight-api-client.cjs.LICENSE.txt +1 -0
- package/dist/cocolight-api-client.mjs.js +2 -1
- package/dist/cocolight-api-client.mjs.js.LICENSE.txt +1 -0
- package/package.json +12 -4
- package/src/Api.js +157 -0
- package/src/ApiClient.js +105 -8
- package/src/api/EntityMixin.js +249 -0
- package/src/api/NewsMixin.js +168 -0
- package/src/api/Organization.js +131 -0
- package/src/api/Project.js +131 -0
- package/src/api/User.js +226 -0
- package/src/api/UserApi.js +48 -0
- package/src/api/UserMixin.js +59 -0
- package/src/api/UtilMixin.js +82 -0
- package/src/endpoints.module.js +2 -2
- package/src/error.js +51 -3
- package/src/index.js +5 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@communecter/cocolight-api-client",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.8",
|
|
4
4
|
"description": "Client Axios simplifié pour l'API cocolight",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"scripts": {
|
|
18
18
|
"test": "node --experimental-vm-modules ./node_modules/.bin/jest --config jest.config.js",
|
|
19
19
|
"exemple": "node exemple/exemple.js",
|
|
20
|
+
"exemple-api": "node exemple/exemple-api.js",
|
|
20
21
|
"lint": "eslint ./src ./exemple ./scripts --ext .js",
|
|
21
22
|
"lint:fix": "eslint ./src ./scripts --ext .js --fix",
|
|
22
23
|
"build:browser": "webpack --config webpack.config.standalone.js",
|
|
@@ -28,7 +29,10 @@
|
|
|
28
29
|
"generate:module:publish": "node ./scripts/transform-json-module.publish.js",
|
|
29
30
|
"generate:doc": "node ./scripts/generate-doc.js",
|
|
30
31
|
"generate:test": "node ./scripts/generate-tests.js",
|
|
31
|
-
"generate:testdata": "node ./scripts/generate-test-data.js"
|
|
32
|
+
"generate:testdata": "node ./scripts/generate-test-data.js",
|
|
33
|
+
"generate:reponses": "node ./scripts/generate-constant-response-200.js",
|
|
34
|
+
"generate:methodeapi": "node ./scripts/generate-methode-api.js",
|
|
35
|
+
"generate:ajv-standalone": "node ./scripts/generate-validate-function-ajv.js"
|
|
32
36
|
},
|
|
33
37
|
"keywords": [
|
|
34
38
|
"communecter",
|
|
@@ -46,25 +50,28 @@
|
|
|
46
50
|
"README.md"
|
|
47
51
|
],
|
|
48
52
|
"peerDependencies": {
|
|
53
|
+
"@segment/ajv-human-errors": "^2.15.0",
|
|
49
54
|
"ajv": "^8.17.1",
|
|
50
55
|
"ajv-formats": "^3.0.1",
|
|
51
56
|
"axios": "^1.4.0",
|
|
52
57
|
"axios-retry": "^4.5.0",
|
|
53
58
|
"ejson": "^2.2.3",
|
|
54
59
|
"events": "^3.3.0",
|
|
60
|
+
"jwt-decode": "^4.0.0",
|
|
55
61
|
"pino": "^9.6.0",
|
|
56
62
|
"pino-pretty": "^13.0.0",
|
|
57
|
-
"
|
|
63
|
+
"file-type": "^20.4.1"
|
|
58
64
|
},
|
|
59
65
|
"devDependencies": {
|
|
60
66
|
"@babel/core": "^7.26.10",
|
|
61
67
|
"@babel/preset-env": "^7.26.9",
|
|
62
68
|
"@eslint/js": "^9.23.0",
|
|
69
|
+
"@segment/ajv-human-errors": "^2.15.0",
|
|
63
70
|
"ajv": "^8.17.1",
|
|
64
71
|
"ajv-formats": "^3.0.1",
|
|
65
72
|
"axios": "^1.4.0",
|
|
66
73
|
"axios-retry": "^4.5.0",
|
|
67
|
-
"
|
|
74
|
+
"file-type": "^20.4.1",
|
|
68
75
|
"babel-jest": "^29.7.0",
|
|
69
76
|
"babel-loader": "^10.0.0",
|
|
70
77
|
"ejson": "^2.2.3",
|
|
@@ -73,6 +80,7 @@
|
|
|
73
80
|
"events": "^3.3.0",
|
|
74
81
|
"globals": "^16.0.0",
|
|
75
82
|
"jest": "^29.7.0",
|
|
83
|
+
"jwt-decode": "^4.0.0",
|
|
76
84
|
"nodemon": "^3.1.9",
|
|
77
85
|
"pino": "^9.6.0",
|
|
78
86
|
"pino-pretty": "^13.0.0",
|
package/src/Api.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Api.js
|
|
2
|
+
import { Organization } from "./api/Organization.js";
|
|
3
|
+
import { Project } from "./api/Project.js";
|
|
4
|
+
import { User } from "./api/User.js";
|
|
5
|
+
import { UserApi } from "./api/UserApi.js";
|
|
6
|
+
import { ApiAuthenticationError, ApiClientError } from "./error.js";
|
|
7
|
+
|
|
8
|
+
export default class Api {
|
|
9
|
+
/**
|
|
10
|
+
* Authentifie l'utilisateur et retourne une instance d'Api.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} email - L'adresse email.
|
|
13
|
+
* @param {string} password - Le mot de passe.
|
|
14
|
+
* @param {Object} options - Options pour l'ApiClient (baseURL, debug, etc.)
|
|
15
|
+
* @returns {Promise<Api>}
|
|
16
|
+
*/
|
|
17
|
+
static async userLogin(email, password, options) {
|
|
18
|
+
const userApi = Api.userApi(options);
|
|
19
|
+
return await Api.userApiLogin(userApi, email, password);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Creates an instance of the UserApi class with the provided options.
|
|
24
|
+
*
|
|
25
|
+
* @param {Object} options - Configuration options for initializing the UserApi instance.
|
|
26
|
+
* @returns {UserApi} An instance of the UserApi class.
|
|
27
|
+
* @throws {Error} Throws an error if the UserApi instance cannot be created.
|
|
28
|
+
*/
|
|
29
|
+
static userApi(options) {
|
|
30
|
+
try {
|
|
31
|
+
const userApi = new UserApi(options);
|
|
32
|
+
return userApi;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
console.error("[Api.userApi] Erreur lors de la création d'un objet utilisateur :", error.message);
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Logs in a user using the provided userApi instance, email, and password.
|
|
41
|
+
*
|
|
42
|
+
* @param {Object} userApi - The API instance used for user authentication.
|
|
43
|
+
* @param {string} email - The email address of the user.
|
|
44
|
+
* @param {string} password - The password of the user.
|
|
45
|
+
* @returns {Promise<Api>} A promise that resolves to an instance of the Api class
|
|
46
|
+
* initialized with the logged-in user and the API client.
|
|
47
|
+
* @throws {ApiAuthenticationError} If the login fails due to authentication issues.
|
|
48
|
+
* @throws {Error} If an unexpected error occurs during the login process.
|
|
49
|
+
*/
|
|
50
|
+
static async userApiLogin(userApi, email, password) {
|
|
51
|
+
try {
|
|
52
|
+
const loggedUser = await userApi.login(email, password);
|
|
53
|
+
return new Api(loggedUser, userApi.client);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if(error instanceof ApiClientError) {
|
|
56
|
+
if(error?.details?.error) {
|
|
57
|
+
throw new ApiAuthenticationError(error.details.error, error.status, error.details);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Construit une instance d'Api.
|
|
66
|
+
*
|
|
67
|
+
* @param {User|null} loggedUser - L'utilisateur connecté ou null.
|
|
68
|
+
* @param {ApiClient} client - L'instance d'ApiClient.
|
|
69
|
+
*/
|
|
70
|
+
constructor(loggedUser, client) {
|
|
71
|
+
this._loggedUser = loggedUser;
|
|
72
|
+
this._client = client;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Retourne l'utilisateur connecté.
|
|
77
|
+
*
|
|
78
|
+
* @returns {User} L'utilisateur connecté.
|
|
79
|
+
*/
|
|
80
|
+
me() {
|
|
81
|
+
if (!this._loggedUser) {
|
|
82
|
+
throw new ApiAuthenticationError("Accès refusé : utilisateur non authentifié.");
|
|
83
|
+
}
|
|
84
|
+
return this._loggedUser;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Crée une instance User pour un utilisateur donné (autre que le connecté).
|
|
89
|
+
*
|
|
90
|
+
* @param {Object} userData - Les données de l'utilisateur public.
|
|
91
|
+
* @returns {User}
|
|
92
|
+
*/
|
|
93
|
+
user(userData) {
|
|
94
|
+
try {
|
|
95
|
+
return new User(this._client, userData);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
console.error("[Api.user] Erreur lors de la création d'un objet utilisateur public :", error.message);
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Creates an Organization object and optionally retrieves its profile.
|
|
105
|
+
*
|
|
106
|
+
* @param {Object} organizationData - The data required to initialize the Organization object.
|
|
107
|
+
* @param {Object} [options={ getProfile: true }] - Additional options for the organization creation.
|
|
108
|
+
* @param {boolean} [options.getProfile=true] - Whether to fetch the organization's profile after creation.
|
|
109
|
+
* @returns {Promise<Organization>} A promise that resolves to the created Organization object.
|
|
110
|
+
* @throws {Error} Throws an error if the organization creation or profile retrieval fails.
|
|
111
|
+
*/
|
|
112
|
+
async organization(organizationData, options = { getProfile: true }) {
|
|
113
|
+
try {
|
|
114
|
+
const oraganization = new Organization(this._client, organizationData);
|
|
115
|
+
if (options.getProfile) {
|
|
116
|
+
await oraganization.getProfil();
|
|
117
|
+
}
|
|
118
|
+
return oraganization;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
console.error("[Api.organization] Erreur lors de la création d'un objet organisation :", error.message);
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Creates a new Project instance and optionally retrieves its profile.
|
|
127
|
+
*
|
|
128
|
+
* @param {Object} projectData - The data used to initialize the Project instance.
|
|
129
|
+
* @param {Object} [options={ getProfile: true }] - Additional options for project creation.
|
|
130
|
+
* @param {boolean} [options.getProfile=true] - Whether to retrieve the project's profile after creation.
|
|
131
|
+
* @returns {Promise<Project>} A promise that resolves to the created Project instance.
|
|
132
|
+
* @throws {Error} If an error occurs during project creation or profile retrieval.
|
|
133
|
+
*/
|
|
134
|
+
async project(projectData, options = { getProfile: true }) {
|
|
135
|
+
try {
|
|
136
|
+
const project = new Project(this._client, projectData);
|
|
137
|
+
if (options.getProfile) {
|
|
138
|
+
await project.getProfil();
|
|
139
|
+
}
|
|
140
|
+
return project;
|
|
141
|
+
} catch (error) {
|
|
142
|
+
console.error("[Api.project] Erreur lors de la création d'un objet projet :", error.message);
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Retourne l'instance d'ApiClient.
|
|
149
|
+
*
|
|
150
|
+
* @returns {ApiClient}
|
|
151
|
+
*/
|
|
152
|
+
|
|
153
|
+
get client() {
|
|
154
|
+
return this._client;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
}
|
package/src/ApiClient.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from "events";
|
|
2
2
|
|
|
3
|
+
import { AggregateAjvError } from "@segment/ajv-human-errors";
|
|
3
4
|
import Ajv from "ajv";
|
|
4
5
|
import addFormats from "ajv-formats";
|
|
5
6
|
import axios from "axios";
|
|
@@ -10,7 +11,7 @@ import pino from "pino";
|
|
|
10
11
|
|
|
11
12
|
import MongoID from "./EJSONType.js";
|
|
12
13
|
import endpointsJson from "./endpoints.module.js";
|
|
13
|
-
import { ApiClientError, CircuitBreakerError } from "./error.js";
|
|
14
|
+
import { ApiClientError, ApiResponseError, ApiValidationError, CircuitBreakerError } from "./error.js";
|
|
14
15
|
|
|
15
16
|
EJSON.addType("oid", value => {
|
|
16
17
|
return new MongoID.ObjectID(value);
|
|
@@ -74,7 +75,7 @@ export default class ApiClient extends EventEmitter {
|
|
|
74
75
|
};
|
|
75
76
|
|
|
76
77
|
// AJV
|
|
77
|
-
this._ajv = new Ajv({ strict: false, useDefaults: true });
|
|
78
|
+
this._ajv = new Ajv({ strict: false, useDefaults: true, allErrors: true, verbose: true });
|
|
78
79
|
addFormats(this._ajv);
|
|
79
80
|
|
|
80
81
|
// Pino logger
|
|
@@ -190,6 +191,16 @@ export default class ApiClient extends EventEmitter {
|
|
|
190
191
|
return this._refreshToken;
|
|
191
192
|
}
|
|
192
193
|
|
|
194
|
+
/**
|
|
195
|
+
* Indique si le client est connecté.
|
|
196
|
+
* On considère que le client est connecté si un token d'accès (_accessToken) est défini.
|
|
197
|
+
*
|
|
198
|
+
* @returns {boolean} True si connecté, false sinon.
|
|
199
|
+
*/
|
|
200
|
+
get isConnected() {
|
|
201
|
+
return !!this._accessToken;
|
|
202
|
+
}
|
|
203
|
+
|
|
193
204
|
/**
|
|
194
205
|
* Extrait l'identifiant depuis un JWT.
|
|
195
206
|
*
|
|
@@ -202,10 +213,10 @@ export default class ApiClient extends EventEmitter {
|
|
|
202
213
|
// Décodage du token grâce à jwt-decode
|
|
203
214
|
const payload = jwtDecode(token);
|
|
204
215
|
// L'identifiant peut être dans "id" ou "userId"
|
|
205
|
-
this._logger.
|
|
216
|
+
this._logger.debug("[ApiClient] Payload décodé :", payload);
|
|
206
217
|
return payload.id || payload.userId || null;
|
|
207
218
|
} catch (err) {
|
|
208
|
-
this._logger.error("[ApiClient] Erreur lors du décodage du token :", err
|
|
219
|
+
this._logger.error("[ApiClient] Erreur lors du décodage du token :", err);
|
|
209
220
|
return null;
|
|
210
221
|
}
|
|
211
222
|
}
|
|
@@ -232,6 +243,8 @@ export default class ApiClient extends EventEmitter {
|
|
|
232
243
|
}
|
|
233
244
|
return false;
|
|
234
245
|
} catch (err) {
|
|
246
|
+
// Si on a une erreur, on reset la session
|
|
247
|
+
this.resetSession();
|
|
235
248
|
this._logger.error(`[ApiClient] Refresh Error : ${err.message}`);
|
|
236
249
|
return false;
|
|
237
250
|
}
|
|
@@ -458,6 +471,23 @@ export default class ApiClient extends EventEmitter {
|
|
|
458
471
|
return obj;
|
|
459
472
|
}
|
|
460
473
|
|
|
474
|
+
/**
|
|
475
|
+
* Safely calls an asynchronous function and handles any errors that occur.
|
|
476
|
+
* Logs the error message using the instance's logger before re-throwing the error.
|
|
477
|
+
*
|
|
478
|
+
* @param {Function} fn - The asynchronous function to be called.
|
|
479
|
+
* @param {...any} args - The arguments to pass to the function.
|
|
480
|
+
* @returns {Promise<any>} The result of the asynchronous function.
|
|
481
|
+
* @throws {Error} Re-throws any error that occurs during the function execution.
|
|
482
|
+
*/
|
|
483
|
+
async safeCall(fn, ...args) {
|
|
484
|
+
try {
|
|
485
|
+
return await fn(...args);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
this._logger.error(`[ApiClient.safeCall] Erreur: ${error.message}`);
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
461
491
|
|
|
462
492
|
/**
|
|
463
493
|
* Calls an API endpoint with the specified parameters.
|
|
@@ -523,8 +553,9 @@ export default class ApiClient extends EventEmitter {
|
|
|
523
553
|
const valid = validatePathParams(pathParams);
|
|
524
554
|
|
|
525
555
|
if (!valid) {
|
|
556
|
+
const errorMessages = this._ajvErrorHuman(validatePathParams.errors);
|
|
526
557
|
this.emit("validationError", { stage: "pathParams", errors: validatePathParams.errors });
|
|
527
|
-
throw new
|
|
558
|
+
throw new ApiValidationError("Path parameter validation failed.", 400, errorMessages, validatePathParams.errors);
|
|
528
559
|
}
|
|
529
560
|
|
|
530
561
|
resolvedParams = this._resolveSpecialValuesInPlace(pathParams);
|
|
@@ -551,8 +582,9 @@ export default class ApiClient extends EventEmitter {
|
|
|
551
582
|
const validateRequest = this._ajv.compile(schemaToCompile);
|
|
552
583
|
const valid = validateRequest(cleanedData);
|
|
553
584
|
if (!valid) {
|
|
585
|
+
const errorMessages = this._ajvErrorHuman(validateRequest.errors);
|
|
554
586
|
this.emit("validationError", { stage: "request", errors: validateRequest.errors });
|
|
555
|
-
throw new
|
|
587
|
+
throw new ApiValidationError("Request validation failed.", 400, errorMessages, validateRequest.errors);
|
|
556
588
|
}
|
|
557
589
|
|
|
558
590
|
data = this._resolveSpecialValuesInPlace(cleanedData, resolvedParams);
|
|
@@ -583,8 +615,9 @@ export default class ApiClient extends EventEmitter {
|
|
|
583
615
|
const validateResponse = this._ajv.compile(schema);
|
|
584
616
|
const valid = validateResponse(response.data);
|
|
585
617
|
if (!valid) {
|
|
618
|
+
const errorMessages = this._ajvErrorHuman(validateResponse.errors);
|
|
586
619
|
this.emit("validationError", { stage: "response", errors: validateResponse.errors });
|
|
587
|
-
throw new
|
|
620
|
+
throw new ApiValidationError("Response validation failed.", status, errorMessages, validateResponse.errors);
|
|
588
621
|
}
|
|
589
622
|
}
|
|
590
623
|
}
|
|
@@ -645,10 +678,74 @@ export default class ApiClient extends EventEmitter {
|
|
|
645
678
|
return response;
|
|
646
679
|
} catch (error) {
|
|
647
680
|
this._updateCircuitBreakerError();
|
|
648
|
-
|
|
681
|
+
this._logger.error(`[ApiClient] Erreur lors de l'appel de ${constant}: ${error.message}`);
|
|
682
|
+
throw new ApiClientError(
|
|
683
|
+
`Erreur lors de l'appel de l'API : ${error.message}`,
|
|
684
|
+
error.response ? error.response.status : 500,
|
|
685
|
+
error.response ? error.response.data : null
|
|
686
|
+
);
|
|
649
687
|
}
|
|
650
688
|
}
|
|
651
689
|
|
|
690
|
+
/**
|
|
691
|
+
* Converts AJV (Another JSON Schema Validator) errors into human-readable messages.
|
|
692
|
+
*
|
|
693
|
+
* @param {Array} errors - An array of AJV validation error objects.
|
|
694
|
+
* @returns {Array<string>} An array of human-readable error messages extracted from the AJV errors.
|
|
695
|
+
*/
|
|
696
|
+
_ajvErrorHuman(errors){
|
|
697
|
+
const errorsMessages = new AggregateAjvError(errors);
|
|
698
|
+
const messages = errorsMessages.errors.map(({ message }) => message);
|
|
699
|
+
return messages;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Checks the API response for errors and throws an `ApiResponseError` if any are found.
|
|
704
|
+
*
|
|
705
|
+
* This method examines the `response.data` object to determine if it contains
|
|
706
|
+
* error information. It handles both standard and nested error cases:
|
|
707
|
+
*
|
|
708
|
+
* - Standard case: If `data.result` is a boolean and is `false`, an error is thrown.
|
|
709
|
+
* - Nested case: If `data.resultErrors` exists and contains a `result` property
|
|
710
|
+
* that is a boolean and is `false`, an error is thrown.
|
|
711
|
+
*
|
|
712
|
+
* If no errors are found, the original `response` is returned.
|
|
713
|
+
*
|
|
714
|
+
* @param {Object} response - The API response object to check.
|
|
715
|
+
* @param {Object} response.data - The data payload of the response.
|
|
716
|
+
* @param {number} response.status - The HTTP status code of the response.
|
|
717
|
+
* @throws {ApiResponseError} If an error is detected in the response data.
|
|
718
|
+
* @returns {Object} The original `response` object if no errors are found.
|
|
719
|
+
*/
|
|
720
|
+
checkAndThrowApiResponseError(response) {
|
|
721
|
+
const data = response.data;
|
|
722
|
+
if (!data || typeof data !== "object") {
|
|
723
|
+
return response;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// Cas standard : vérifie si data.result vaut false
|
|
727
|
+
if (typeof data.result === "boolean" && data.result === false) {
|
|
728
|
+
throw new ApiResponseError(
|
|
729
|
+
data.msg || "Erreur inconnue",
|
|
730
|
+
response.status,
|
|
731
|
+
data
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// Cas imbriqué : vérifie si data.resultErrors existe et contient une erreur
|
|
736
|
+
if (data.resultErrors && typeof data.resultErrors === "object") {
|
|
737
|
+
if (typeof data.resultErrors.result === "boolean" && data.resultErrors.result === false) {
|
|
738
|
+
throw new ApiResponseError(
|
|
739
|
+
data.resultErrors.msg || "Erreur inconnue",
|
|
740
|
+
response.status,
|
|
741
|
+
data
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
return response;
|
|
747
|
+
}
|
|
748
|
+
|
|
652
749
|
/**
|
|
653
750
|
* Réinitialise complètement la session de l'utilisateur :
|
|
654
751
|
* - Token d'accès
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { ApiResponseError } from "../error.js";
|
|
2
|
+
|
|
3
|
+
// EntityMixin.js
|
|
4
|
+
export const EntityMixin = {
|
|
5
|
+
/**
|
|
6
|
+
* Résout l'identifiant de l'entité si seul le slug est fourni.
|
|
7
|
+
* @param {string} type - Le type d'entité (ex : "citoyens", "organizations", "projects").
|
|
8
|
+
* @returns {Promise<string>} L'identifiant résolu.
|
|
9
|
+
*/
|
|
10
|
+
async resolveId(type) {
|
|
11
|
+
if (!this.id && this.slug) {
|
|
12
|
+
try {
|
|
13
|
+
const data = await this._getElementsKey({
|
|
14
|
+
pathParams:{
|
|
15
|
+
slug: this.slug
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
if(data?.contextId && data?.contextType === type) {
|
|
19
|
+
this._id(data.contextId);
|
|
20
|
+
} else {
|
|
21
|
+
throw new ApiResponseError(`Le slug ${this.slug} ne correspond pas à un ${type}`, 200, data);
|
|
22
|
+
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if(error instanceof ApiResponseError) {
|
|
25
|
+
if(error?.responseData?.contextType !== type) {
|
|
26
|
+
throw error;
|
|
27
|
+
} else {
|
|
28
|
+
throw new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${this.slug}`, error.status, error.responseData);
|
|
29
|
+
}
|
|
30
|
+
} else {
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return this.id;
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Récupère le profil public de l'entité.
|
|
40
|
+
* @returns {Promise<Object>} Les données du profil public.
|
|
41
|
+
*/
|
|
42
|
+
async getPublicProfile() {
|
|
43
|
+
await this.resolveId(this.getEntityType());
|
|
44
|
+
return this._getElementsAbout({ pathParams: { id: this.id, type: this.getEntityType() } });
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Obtenir les éléments liés : Récupère les informations détaillées d'un élément et de ses éléments liés.
|
|
49
|
+
* Constant : GET_ELEMENTS_ABOUT
|
|
50
|
+
* @param {Object} data - Les données à envoyer.
|
|
51
|
+
* @param {string} data.tpl - Template utilisé (ex: ficheInfoElement) (default: "ficheInfoElement")
|
|
52
|
+
* @param {Object} data.pathParams - Les paramètres de chemin.
|
|
53
|
+
* @param {string} data.pathParams.type - Type d'entité (default: "citoyens")
|
|
54
|
+
* @param {string} data.pathParams.id - ID de l'utilisateur ou de l'entité
|
|
55
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
56
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
57
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
58
|
+
*/
|
|
59
|
+
async _getElementsAbout(data = {}) {
|
|
60
|
+
return this.call("GET_ELEMENTS_ABOUT", data);
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Récuperer l'id et la collection d'un element en fonction du slug : Récuperer l'id et la collection d'un element en fonction du slug
|
|
65
|
+
* Constant : GET_ELEMENTS_KEY
|
|
66
|
+
* @param {Object} data.pathParams - Les paramètres de chemin.
|
|
67
|
+
* @param {string} data.pathParams.slug - Slug de l'élément à récupérer
|
|
68
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
69
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
70
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
71
|
+
*/
|
|
72
|
+
async _getElementsKey(data = {}) {
|
|
73
|
+
return this.call("GET_ELEMENTS_KEY", data);
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Mettre à jour l'image de profil : Permet de mettre à jour l'image de profil d'un utilisateur ou d'une entité.
|
|
78
|
+
* Constant : PROFIL_IMAGE
|
|
79
|
+
* @param {Object} data - Les données à envoyer.
|
|
80
|
+
* @param {undefined} data.profil_avatar - Fichier image de profil au format binaire
|
|
81
|
+
* @param {Object} data.pathParams - Les paramètres de chemin.
|
|
82
|
+
* @param {string} data.pathParams.folder - Type d'entité (default: "citoyens")
|
|
83
|
+
* @param {string} data.pathParams.ownerId - ID de l'utilisateur ou de l'entité
|
|
84
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
85
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
86
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
87
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
88
|
+
*/
|
|
89
|
+
async _profilImage(data = {}) {
|
|
90
|
+
return this.callIsConnected("PROFIL_IMAGE", data);
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Mettre à jour les paramètres d'un élément : Mise à jour des paramètres spécifiques d'un élément.
|
|
95
|
+
* Constant : UPDATE_SETTINGS
|
|
96
|
+
* @param {Object} data - Les données à envoyer.
|
|
97
|
+
* @param {string} data.type - data.type
|
|
98
|
+
* @param {undefined} data.value - data.value
|
|
99
|
+
* @param {string} data.typeEntity - Type d'élément (citoyens, projects, organizations) (default: "citoyens")
|
|
100
|
+
* @param {string} data.idEntity - Id de l'élément
|
|
101
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
102
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
103
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
104
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
105
|
+
*/
|
|
106
|
+
async _updateSettings(data = {}) {
|
|
107
|
+
return this.callIsConnected("UPDATE_SETTINGS", data);
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Mettre à jour la description d'un élément : Permet de mettre à jour la description courte et complète d'un élément.
|
|
112
|
+
* Constant : UPDATE_BLOCK_DESCRIPTION
|
|
113
|
+
* @param {Object} data - Les données à envoyer.
|
|
114
|
+
* @param {string} data.block - Nom du bloc à mettre à jour (doit être 'descriptions') (default: "descriptions")
|
|
115
|
+
* @param {string} data.typeElement - Type d'élément (citoyens, projects, organizations) (default: "citoyens")
|
|
116
|
+
* @param {string} data.id - ID de l'élément concerné
|
|
117
|
+
* @param {string | null} data.scope - Périmètre de mise à jour (default: "")
|
|
118
|
+
* @param {string} data.descMentions - Mentions dans la description (default: "")
|
|
119
|
+
* @param {string} data.shortDescription - Courte description
|
|
120
|
+
* @param {string} data.description - Description complète
|
|
121
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
122
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
123
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
124
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
125
|
+
*/
|
|
126
|
+
async _updateBlockDescription(data = {}) {
|
|
127
|
+
return this.callIsConnected("UPDATE_BLOCK_DESCRIPTION", data);
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Mettre à jour les informations d'un élément : Permet de mettre à jour les informations générales d'un élément (nom, contacts, etc.).
|
|
132
|
+
* Constant : UPDATE_BLOCK_INFO
|
|
133
|
+
* @param {Object} data - Les données à envoyer.
|
|
134
|
+
* @param {string} data.block - Nom du bloc à mettre à jour (doit être 'info') (default: "info")
|
|
135
|
+
* @param {string} data.typeElement - Type d'élément (citoyens, projects, organizations) (default: "citoyens")
|
|
136
|
+
* @param {string} data.id - ID de l'élément concerné
|
|
137
|
+
* @param {string} data.scope - Périmètre de mise à jour (default: "")
|
|
138
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
139
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
140
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
141
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
142
|
+
*/
|
|
143
|
+
async _updateBlockInfo(data = {}) {
|
|
144
|
+
return this.callIsConnected("UPDATE_BLOCK_INFO", data);
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Mettre à jour les réseaux sociaux d'un élément : Permet de mettre à jour les liens vers les réseaux sociaux d'un élément.
|
|
149
|
+
* Constant : UPDATE_BLOCK_SOCIAL
|
|
150
|
+
* @param {Object} data - Les données à envoyer.
|
|
151
|
+
* @param {string} data.block - Nom du bloc à mettre à jour (doit être 'network') (default: "network")
|
|
152
|
+
* @param {string} data.typeElement - Type d'élément (citoyens, projects, organizations) (default: "citoyens")
|
|
153
|
+
* @param {string} data.id - ID de l'élément concerné
|
|
154
|
+
* @param {string} data.scope - Périmètre de mise à jour (default: "")
|
|
155
|
+
* @param {string} data.gitlab - Compte Gitlab
|
|
156
|
+
* @param {string} data.github - Compte Github
|
|
157
|
+
* @param {string} data.twitter - Compte Twitter
|
|
158
|
+
* @param {string} data.facebook - Compte Facebook
|
|
159
|
+
* @param {string} data.instagram - Compte Instagram
|
|
160
|
+
* @param {string} data.diaspora - Compte Diaspora
|
|
161
|
+
* @param {string} data.mastodon - Compte Mastodon
|
|
162
|
+
* @param {string} data.telegram - Compte Telegram
|
|
163
|
+
* @param {string} data.signal - Compte Signal
|
|
164
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
165
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
166
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
167
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
168
|
+
*/
|
|
169
|
+
async _updateBlockSocial(data = {}) {
|
|
170
|
+
return this.callIsConnected("UPDATE_BLOCK_SOCIAL", data);
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Mettre à jour les localités d'un élément : Permet de mettre à jour l'adresse et les informations géographiques d'un élément.
|
|
175
|
+
* Constant : UPDATE_BLOCK_LOCALITY
|
|
176
|
+
* @param {Object} data - Les données à envoyer.
|
|
177
|
+
* @param {string} data.block - Nom du bloc à mettre à jour (doit être 'localities') (default: "localities")
|
|
178
|
+
* @param {string} data.typeElement - Type d'élément (default: "citoyens")
|
|
179
|
+
* @param {string} data.id - ID de l'élément concerné
|
|
180
|
+
* @param {string} data.scope - Périmètre de mise à jour (default: "")
|
|
181
|
+
* @param {object} data.geo - Coordonnées géographiques
|
|
182
|
+
* @param {string} data.geo.@type - data.geo.@type
|
|
183
|
+
* @param {string | number} data.geo.latitude - data.geo.latitude
|
|
184
|
+
* @param {string | number} data.geo.longitude - data.geo.longitude
|
|
185
|
+
* @param {object} data.geoPosition - Position géographique GeoJSON
|
|
186
|
+
* @param {string} data.geoPosition.type - Type GeoJSON (doit être 'Point')
|
|
187
|
+
* @param {Array<number>} data.geoPosition.coordinates - Tableau contenant [longitude, latitude]
|
|
188
|
+
* @param {boolean} data.geoPosition.float - Indicateur pour forcer la conversion en float côté serveur (default: true)
|
|
189
|
+
* @param {object} data.address - data.address
|
|
190
|
+
* @param {string} data.address.@type - data.address.@type
|
|
191
|
+
* @param {string} data.address.addressCountry - data.address.addressCountry
|
|
192
|
+
* @param {string} data.address.codeInsee - data.address.codeInsee
|
|
193
|
+
* @param {string} data.address.addressLocality - data.address.addressLocality
|
|
194
|
+
* @param {string} data.address.localityId - data.address.localityId
|
|
195
|
+
* @param {string} data.address.level1 - data.address.level1
|
|
196
|
+
* @param {string} data.address.level1Name - data.address.level1Name
|
|
197
|
+
* @param {string} data.address.level3 - ID du département. Peut être vide pour les pays étrangers.
|
|
198
|
+
* @param {string} data.address.level3Name - Nom du département. Peut être vide pour les pays étrangers.
|
|
199
|
+
* @param {string} data.address.level4 - ID de la commune. Peut être vide pour les pays étrangers.
|
|
200
|
+
* @param {string} data.address.level4Name - Nom de la commune. Peut être vide pour les pays étrangers.
|
|
201
|
+
* @param {string} data.address.postalCode - data.address.postalCode
|
|
202
|
+
* @param {string} data.address.streetAddress - data.address.streetAddress
|
|
203
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
204
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
205
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
206
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
207
|
+
*/
|
|
208
|
+
async _updateBlockLocality(data = {}) {
|
|
209
|
+
return this.callIsConnected("UPDATE_BLOCK_LOCALITY", data);
|
|
210
|
+
},
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Mettre à jour le slug d'un élément : Permet de mettre à jour le slug pour une URL simplifiée.
|
|
214
|
+
* Constant : UPDATE_BLOCK_SLUG
|
|
215
|
+
* @param {Object} data - Les données à envoyer.
|
|
216
|
+
* @param {string} data.block - Nom du bloc à mettre à jour (doit être 'info') (default: "info")
|
|
217
|
+
* @param {string} data.typeElement - Type d'élément (citoyens, projects, organizations) (default: "citoyens")
|
|
218
|
+
* @param {string} data.id - ID de l'élément concerné
|
|
219
|
+
* @param {string} data.scope - data.scope (default: "")
|
|
220
|
+
* @param {string} data.slug - Slug simplifié pour URL
|
|
221
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
222
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
223
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
224
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
225
|
+
*/
|
|
226
|
+
async _updateBlockSlug(data = {}) {
|
|
227
|
+
return this.callIsConnected("UPDATE_BLOCK_SLUG", data);
|
|
228
|
+
},
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Vérifier l'état d'une URL : Vérifie si une URL (slug) est valide ou disponible.
|
|
232
|
+
* Constant : CHECK
|
|
233
|
+
* @param {Object} data - Les données à envoyer.
|
|
234
|
+
* @param {string} data.block - Nom du bloc (default: "info")
|
|
235
|
+
* @param {string} data.id - ID de l'élément
|
|
236
|
+
* @param {string} data.type - Type d'élément (default: "citoyens")
|
|
237
|
+
* @param {string} data.slug - Slug à vérifier
|
|
238
|
+
* @returns {Promise<Object>} - Les données de réponse.
|
|
239
|
+
* @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
|
|
240
|
+
* @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
|
|
241
|
+
* @throws {Error} - En cas d'erreur inattendue.
|
|
242
|
+
*/
|
|
243
|
+
async _check(data = {}) {
|
|
244
|
+
return this.callIsConnected("CHECK", data);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
};
|
|
249
|
+
|