@communecter/cocolight-api-client 1.0.20 → 1.0.21

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.
@@ -1,300 +0,0 @@
1
- import ObjectID from "bson-objectid";
2
- // import { fileTypeFromBuffer } from "file-type";
3
- import pkg from "file-type";
4
- const { fromBuffer } = pkg;
5
-
6
- import { ApiAuthenticationError, ApiValidationError } from "../error.js";
7
-
8
- // UtilMixin.js
9
- export const UtilMixin = {
10
-
11
- /**
12
- * Appelle une méthode de l'API.
13
- *
14
- * @param {string} constant - Le nom de la méthode à appeler.
15
- * @param {object} data - Les données à passer à la méthode.
16
- * @returns {Promise<any>} - La promesse de la méthode appelée.
17
- * @throws {ApiValidationError} - Si une erreur se produit lors de l'appel de l'API.
18
- * @throws {ApiResponseError} - Si une erreur se produit lors de l'appel de l'API.
19
- * @throws {ApiClientError} - Si l'utilisateur n'est pas authentifié.
20
- */
21
- async call(constant, data = {}) {
22
- return this.apiClient.safeCall(async () => {
23
- const response = await this.apiClient.callEndpoint(constant, data);
24
- this.apiClient.checkAndThrowApiResponseError(response);
25
- return response.data;
26
- });
27
- },
28
-
29
- /**
30
- * Appelle une méthode de l'API si l'utilisateur n'est pas connecté.
31
- *
32
- * @param {string} constant - Le nom de la méthode à appeler.
33
- * @param {object} data - Les données à passer à la méthode.
34
- * @returns {Promise<any>} - La promesse de la méthode appelée.
35
- * @throws {ApiAuthenticationError} - Si l'utilisateur est connecté.
36
- * @throws {ApiValidationError} - Si une erreur se produit lors de l'appel de l'API.
37
- * @throws {ApiResponseError} - Si une erreur se produit lors de l'appel de l'API.
38
- * @throws {ApiClientError} - Si une erreur se produit lors de l'appel de l'API.
39
- */
40
- async callNoConnected(constant, data = {}) {
41
- if(this.isConnected) {
42
- throw new ApiAuthenticationError("Vous devez ne devez pas être connecté pour faire cette action.");
43
- }
44
- return this.call(constant, data);
45
- },
46
-
47
- /**
48
- * Appelle une méthode de l'API si l'utilisateur est connecté.
49
- *
50
- * @param {string|function} param - Le nom de la méthode à appeler ou une fonction de rappel.
51
- * @param {object} data - Les données à passer à la méthode.
52
- * @returns {Promise<any>} - La promesse de la méthode appelée.
53
- * @throws {ApiAuthenticationError} - Si l'utilisateur n'est pas connecté.
54
- * @throws {ApiValidationError} - Si une erreur se produit lors de l'appel de l'API.
55
- * @throws {ApiResponseError} - Si une erreur se produit lors de l'appel de l'API.
56
- * @throws {ApiClientError} - Si une erreur se produit lors de l'appel de l'API.
57
- */
58
- async callIsConnected(param, data = {}) {
59
- if(!this.isConnected) {
60
- throw new ApiAuthenticationError("Vous devez être connecté pour faire cette action.");
61
- }
62
- // Si le premier paramètre est une fonction, on l'exécute en tant que callback
63
- if (typeof param === "function") {
64
- return await param();
65
- }
66
- return this.call(param, data);
67
- },
68
-
69
- /**
70
- * Appelle une méthode de l'API si l'utilisateur est lui-même.
71
- *
72
- * @param {string|function} param - Le nom de la méthode à appeler ou une fonction de rappel.
73
- * @param {object} data - Les données à passer à la méthode.
74
- * @returns {Promise<any>} - La promesse de la méthode appelée.
75
- * @throws {ApiAuthenticationError} - Si l'utilisateur n'est pas lui-même.
76
- * @throws {ApiValidationError} - Si une erreur se produit lors de l'appel de l'API.
77
- * @throws {ApiResponseError} - Si une erreur se produit lors de l'appel de l'API.
78
- * @throws {ApiClientError} - Si une erreur se produit lors de l'appel de l'API.
79
- */
80
- async callIsMe(param, data = {}) {
81
- if (!this.isMe) {
82
- throw new ApiAuthenticationError("Vous devez être vous-même pour faire cette action.");
83
- }
84
- // Si le premier paramètre est une fonction, on l'exécute en tant que callback
85
- if (typeof param === "function") {
86
- return await param();
87
- }
88
- // Sinon, on considère qu'il s'agit d'un constant et on appelle la méthode par défaut
89
- return await this.callIsConnected(param, data);
90
- },
91
-
92
- async _validateImage(imageInput){
93
- const image = await this._validateUploadInput(imageInput, {
94
- allowedMimeTypes: ["image/jpeg", "image/png", "image/jpg"],
95
- expectedType: "image"
96
- });
97
- return image;
98
- },
99
-
100
- async _validateFile(fileInput){
101
- const file = await this._validateUploadInput(fileInput, {
102
- allowedMimeTypes: ["application/pdf", "text/plain", "text/csv"],
103
- expectedType: "file"
104
- });
105
- return file;
106
- },
107
-
108
- async _validateUploadInput(input, { allowedMimeTypes = [], expectedType = "any" }) {
109
- if (!input) {
110
- throw new ApiValidationError("Le fichier est requis.");
111
- }
112
-
113
- const isNode = typeof window === "undefined" && typeof process !== "undefined";
114
- let mimeType = "";
115
- let output = input;
116
-
117
- // Navigateur : File
118
- if (typeof File !== "undefined" && input instanceof File) {
119
- mimeType = input.type;
120
- if (!allowedMimeTypes.includes(mimeType)) {
121
- throw new ApiValidationError("Le type du fichier est invalide.");
122
- }
123
- }
124
-
125
- // Navigateur : Blob
126
- else if (typeof Blob !== "undefined" && input instanceof Blob) {
127
- mimeType = input.type;
128
- if (!allowedMimeTypes.includes(mimeType)) {
129
- throw new ApiValidationError("Le type du fichier est invalide.");
130
- }
131
-
132
- const ext = mimeType.split("/")[1] || "bin";
133
- const fileName = `${Date.now()}.${ext}`;
134
- output = new File([input], fileName, { type: mimeType });
135
- }
136
-
137
- // Node.js : Buffer
138
- else if (isNode && Buffer.isBuffer(input)) {
139
- const fileTypeResult = await fromBuffer(input);
140
- mimeType = fileTypeResult?.mime;
141
-
142
- if (!fileTypeResult || !allowedMimeTypes.includes(mimeType)) {
143
- throw new ApiValidationError("Le type du fichier est invalide.");
144
- }
145
-
146
- // Pour un fichier image, on transforme en stream
147
- if (expectedType === "image") {
148
- const ext = fileTypeResult.ext;
149
- const filename = `${Date.now()}.${ext}`;
150
- output = await this._createReadStreamFromBuffer(input, filename, mimeType);
151
- }
152
- }
153
-
154
- // Node.js : ReadableStream
155
- else if (isNode && input?.readable && typeof input._read === "function") {
156
- const previewChunks = [];
157
- const tee = await this._passThrough();
158
- const resultStream = await this._passThrough();
159
-
160
- const MAX_BYTES = 4100;
161
- let bytesRead = 0;
162
-
163
- input.on("data", (chunk) => {
164
- if (bytesRead < MAX_BYTES) {
165
- previewChunks.push(chunk);
166
- bytesRead += chunk.length;
167
- }
168
- });
169
-
170
- input.pipe(tee).pipe(resultStream);
171
- await new Promise((resolve) => setTimeout(resolve, 10));
172
-
173
- const previewBuffer = Buffer.concat(previewChunks);
174
- const fileTypeResult = await fromBuffer(previewBuffer);
175
- mimeType = fileTypeResult?.mime;
176
-
177
- if (!fileTypeResult || !allowedMimeTypes.includes(mimeType)) {
178
- throw new ApiValidationError("Le type du fichier est invalide.");
179
- }
180
-
181
- resultStream.path = `${Date.now()}.${fileTypeResult.ext}`;
182
- resultStream.mimeType = mimeType;
183
- output = resultStream;
184
- }
185
-
186
- else {
187
- throw new ApiValidationError("Type de fichier non reconnu.");
188
- }
189
-
190
- return output;
191
- },
192
-
193
- /**
194
- * Transforme un Buffer en ReadableStream équivalent à fs.createReadStream
195
- * @param {Buffer} buffer - Le buffer contenant les données binaires
196
- * @param {string} filename - Nom de fichier (utilisé dans FormData)
197
- * @param {string} mimeType - Type MIME (utilisé dans FormData)
198
- * @returns {Object} - { stream, filename, mimeType }
199
- */
200
- async _createReadStreamFromBuffer(buffer, filename = "file.bin", mimeType = "application/octet-stream") {
201
- const stream = await this._bufferToReadable(buffer);
202
- stream.path = filename; // 👈 hack pour simuler un vrai fichier ReadStream
203
- stream.mimeType = mimeType;
204
- return stream;
205
- },
206
-
207
- async _bufferToReadable(buffer) {
208
- if (typeof window === "undefined") {
209
- const { bufferToReadable } = await import("../utils/stream-utils.node.js");
210
- return bufferToReadable(buffer);
211
- } else {
212
- throw new Error("bufferToReadable ne doit pas être appelé dans le navigateur");
213
- }
214
- },
215
-
216
- async _passThrough() {
217
- if (typeof window === "undefined") {
218
- const { createPassThrough } = await import("../utils/stream-utils.node.js");
219
- return createPassThrough();
220
- } else {
221
- throw new Error("passThrough ne doit pas être appelé dans le navigateur");
222
- }
223
- },
224
-
225
- // async _bufferToReadable(buffer) {
226
- // if (typeof window === "undefined") {
227
- // const { Readable } = await import("stream");
228
- // return Readable.from(buffer);
229
- // } else {
230
- // throw new Error("bufferToReadable ne doit pas être appelé dans le navigateur");
231
- // }
232
- // },
233
-
234
- // async _passThrough() {
235
- // if (typeof window === "undefined") {
236
- // const { PassThrough } = await import("stream");
237
- // return new PassThrough();
238
- // } else {
239
- // throw new Error("passThrough ne doit pas être appelé dans le navigateur");
240
- // }
241
- // },
242
-
243
- _omitProps(obj, propsToRemove) {
244
- if (!obj || typeof obj !== "object") return {};
245
-
246
- const result = { ...obj };
247
- for (const prop of propsToRemove) {
248
- delete result[prop];
249
- }
250
- return result;
251
- },
252
-
253
- _pickProps(obj, keys, transforms = {}) {
254
- if (!obj || typeof obj !== "object") return {};
255
-
256
- const result = {};
257
-
258
- for (const key of keys) {
259
- if (key in obj) {
260
- const value = obj[key];
261
- if (typeof transforms[key] === "function") {
262
- result[key] = transforms[key](value, obj); // (valeur, objet source)
263
- } else {
264
- result[key] = value;
265
- }
266
- }
267
- }
268
-
269
- return result;
270
- },
271
-
272
- _hasAtLeastOne(obj, keys = []) {
273
- return keys.some((key) => key in obj && obj[key] != null);
274
- },
275
-
276
- _createFilteredProxy(list) {
277
- return new Proxy(list, {
278
- get(target, prop, receiver) {
279
- if (typeof prop === "string" && !isNaN(prop)) {
280
- const active = target.filter(n => !n._isDeleted);
281
- return active[prop];
282
- }
283
- if (prop === "length") {
284
- return target.filter(n => !n._isDeleted).length;
285
- }
286
- if (typeof target[prop] === "function") {
287
- return (...args) => target.filter(n => !n._isDeleted)[prop](...args);
288
- }
289
- return Reflect.get(target, prop, receiver);
290
- }
291
- });
292
- },
293
-
294
- _newId() {
295
- const newId = new ObjectID();
296
- return newId.toString();
297
- }
298
-
299
- };
300
-