@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.
@@ -0,0 +1,48 @@
1
+ // UserApi.js
2
+ import ApiClient from "../ApiClient.js";
3
+ import { ApiResponseError } from "../error.js";
4
+ import { User } from "./User.js";
5
+
6
+ export class UserApi {
7
+ constructor(options) {
8
+ // Injection de dépendance : ApiClient est créé à partir des options
9
+ this.client = new ApiClient(options);
10
+ this.loggedUser = null;
11
+ }
12
+ // Méthode d'authentification : récupère les données utilisateur depuis un endpoint
13
+ async login(email, password) {
14
+ return this.client.safeCall(async () => {
15
+ // Appel à un endpoint d'authentification
16
+ const response = await this.client.callEndpoint("AUTHENTICATE_URL", { email, password });
17
+ // Création d'une instance de LoggedInUser à partir des données reçues
18
+ this.loggedUser = new User(this.client, { id: response.data.user.id }, response.data.user);
19
+ return this.loggedUser;
20
+ });
21
+ }
22
+
23
+ async register({
24
+ name,
25
+ username,
26
+ email,
27
+ pwd,
28
+ } = {}) {
29
+ return this.client.safeCall(async () => {
30
+ const response = await this.client.callEndpoint("PERSON_REGISTER", { name, username, email, pwd });
31
+ if(response?.data?.result === false) {
32
+ throw new ApiResponseError(response.data.msg, response.status, response.data);
33
+ }
34
+ return response.data;
35
+ });
36
+ }
37
+
38
+
39
+ async recoverPassword(email) {
40
+ return this.client.safeCall(async () => {
41
+ const response = await this.client.callEndpoint("PASSWORD_RECOVERY", { email });
42
+ if(response?.data?.result === false) {
43
+ throw new ApiResponseError(response.data.msg, response.status, response.data);
44
+ }
45
+ return response.data;
46
+ });
47
+ }
48
+ }
@@ -0,0 +1,59 @@
1
+ // eslint-disable-next-line no-unused-vars
2
+ import { ApiResponseError } from "../error.js";
3
+
4
+ // UserMixin.js
5
+ export const UserMixin = {
6
+
7
+ /**
8
+ * Récupérer les informations utilisateur : Récupère les informations du profil utilisateur pour un token donné.
9
+ * Constant : ME_INFO_URL
10
+ * @returns {Promise<Object>} - Les données de réponse.
11
+ * @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
12
+ * @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
13
+ * @throws {Error} - En cas d'erreur inattendue.
14
+ */
15
+ async _meInfoUrl() {
16
+ return this.callIsConnected("ME_INFO_URL");
17
+ },
18
+
19
+ /**
20
+ * Changer le mot de passe : Permet de changer le mot de passe d'un utilisateur.
21
+ * Constant : CHANGE_PASSWORD
22
+ * @param {Object} data - Les données à envoyer.
23
+ * @param {string} data.oldPassword - Ancien mot de passe
24
+ * @param {string} data.newPassword - Nouveau mot de passe
25
+ * @param {string} data.newPassword2 - Confirmation du nouveau mot de passe
26
+ * @returns {Promise<Object>} - Les données de réponse.
27
+ * @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
28
+ * @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
29
+ * @throws {Error} - En cas d'erreur inattendue.
30
+ */
31
+ async _changePassword(data = {}) {
32
+ if(data.userId) {
33
+ delete data.userId;
34
+ }
35
+ if(data.mode) {
36
+ delete data.mode;
37
+ }
38
+ return this.callIsConnected("CHANGE_PASSWORD", data);
39
+ },
40
+
41
+ /**
42
+ * Supprimer un compte : Permet de supprimer un compte utilisateur.
43
+ * Constant : DELETE_ACCOUNT
44
+ * @param {Object} data - Les données à envoyer.
45
+ * @param {string} data.reason - Raison de la suppression (default: "")
46
+ * @returns {Promise<Object>} - Les données de réponse.
47
+ * @throws {ApiResponseError} - En cas d'erreur détectée dans la réponse.
48
+ * @throws {ApiAuthenticationError} - En cas d'erreur d'authentification.
49
+ * @throws {Error} - En cas d'erreur inattendue.
50
+ */
51
+ async _deleteAccount(data = {}) {
52
+ if (data.pathParams) {
53
+ delete data.pathParams;
54
+ }
55
+ return this.callIsConnected("DELETE_ACCOUNT", data);
56
+ }
57
+
58
+ };
59
+
@@ -0,0 +1,82 @@
1
+ import { fileTypeFromBuffer } from "file-type";
2
+
3
+ import { ApiAuthenticationError, ApiValidationError } from "../error.js";
4
+
5
+ // UtilMixin.js
6
+ export const UtilMixin = {
7
+
8
+ async call(constant, data = {}) {
9
+ return this.apiClient.safeCall(async () => {
10
+ const response = await this.apiClient.callEndpoint(constant, data);
11
+ this.apiClient.checkAndThrowApiResponseError(response);
12
+ return response.data;
13
+ });
14
+ },
15
+
16
+ async callNoConnected(constant, data = {}) {
17
+ if(this.isConnected) {
18
+ throw new ApiAuthenticationError("Vous devez ne devez pas être connecté pour faire cette action.");
19
+ }
20
+ return this.call(constant, data);
21
+ },
22
+
23
+ async callIsConnected(param, data = {}) {
24
+ if(!this.isConnected) {
25
+ throw new ApiAuthenticationError("Vous devez être connecté pour faire cette action.");
26
+ }
27
+ // Si le premier paramètre est une fonction, on l'exécute en tant que callback
28
+ if (typeof param === "function") {
29
+ return await param();
30
+ }
31
+ return this.call(param, data);
32
+ },
33
+
34
+ async callIsMe(param, data = {}) {
35
+ if (!this.isMe) {
36
+ throw new ApiAuthenticationError("Vous devez être vous-même pour faire cette action.");
37
+ }
38
+ // Si le premier paramètre est une fonction, on l'exécute en tant que callback
39
+ if (typeof param === "function") {
40
+ return await param();
41
+ }
42
+ // Sinon, on considère qu'il s'agit d'un constant et on appelle la méthode par défaut
43
+ return await this.callIsConnected(param, data);
44
+ },
45
+
46
+ async validateImage(image) {
47
+ if (!image) {
48
+ throw new ApiValidationError("Le fichier est requis.");
49
+ }
50
+ let mimeType = "";
51
+
52
+ // Vérification en navigateur : File et Blob
53
+ if (typeof File !== "undefined" && image instanceof File) {
54
+ mimeType = image.type;
55
+ if (!mimeType || !mimeType.startsWith("image/") || !["image/jpg", "image/jpeg", "image/png"].includes(mimeType)) {
56
+ throw new ApiValidationError("Le fichier doit être une image valide.");
57
+ }
58
+ } else if (typeof Blob !== "undefined" && image instanceof Blob) {
59
+ mimeType = image.type;
60
+ // rajouter un name au blob avce timestamp et la bonne extension
61
+ const fileName = `${Date.now()}.${mimeType.split("/")[1]}`;
62
+ image = new File([image], fileName, { type: mimeType });
63
+ console.log(fileName);
64
+
65
+ if (!mimeType || !mimeType.startsWith("image/") || !["image/jpg", "image/jpeg", "image/png"].includes(mimeType)) {
66
+ throw new ApiValidationError("Le fichier doit être une image valide (jpg ou png).");
67
+ }
68
+ }
69
+ // Vérification en Node : image peut être un Buffer
70
+ else if (typeof Buffer !== "undefined" && Buffer.isBuffer(image)) {
71
+ const fileTypeResult = await fileTypeFromBuffer(image);
72
+ if (!fileTypeResult || !fileTypeResult.mime.startsWith("image/") || !["image/jpg", "image/jpeg", "image/png"].includes(fileTypeResult.mime)) {
73
+ throw new ApiValidationError("Le fichier doit être une image valide.");
74
+ }
75
+ mimeType = fileTypeResult.mime;
76
+ } else {
77
+ throw new ApiValidationError("Le fichier doit être de type File (navigateur) ou Buffer (Node).");
78
+ }
79
+ return image;
80
+ }
81
+ };
82
+