polgo-upload-kit 1.1.11 → 1.2.0

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": "polgo-upload-kit",
3
- "version": "1.1.11",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "main": "src/polgoUploadClient.js",
6
6
  "scripts": {
@@ -1,12 +1,95 @@
1
1
  import axios from "axios";
2
2
 
3
+ /**
4
+ * Cliente para upload de arquivos para o serviço Polgo
5
+ * @class PolgoUploadClient
6
+ */
3
7
  class PolgoUploadClient {
4
- constructor(isProd, token, stack) {
5
- this.ambiente = isProd ? "producao" : "dev";
6
- this.url =
7
- "https://mkgplyz3tc.execute-api.us-east-1.amazonaws.com/lambdaUploadProducao/arquivo/upload";
8
- this.stack = stack;
9
- this.token = token;
8
+ /**
9
+ * Inicializa o cliente de upload
10
+ * @param {Object} config - Configurações do cliente
11
+ * @param {boolean} [config.isProd=false] - Define se está em ambiente de produção
12
+ * @param {string} config.token - Token de autorização Bearer
13
+ * @param {string} config.stack - Nome da stack/aplicação
14
+ * @param {string} [config.baseUrl] - URL base personalizada para a API
15
+ * @param {Object} [config.endpoints] - Endpoints personalizados
16
+ * @param {string} [config.endpoints.upload] - Endpoint de upload personalizado
17
+ * @param {string} [config.endpoints.recuperar] - Endpoint de recuperação personalizado
18
+ * @param {string} [config.endpoints.listar] - Endpoint de listagem personalizado
19
+ *
20
+ */
21
+ constructor(config = {}) {
22
+ // Validação de parâmetros obrigatórios
23
+ if (!config.token) {
24
+ throw new Error('Token de autorização é obrigatório');
25
+ }
26
+ if (!config.stack) {
27
+ throw new Error('Stack é obrigatória');
28
+ }
29
+
30
+ // Configurações principais
31
+ this.isProd = config.isProd || false;
32
+ this.ambiente = this.isProd ? "producao" : "dev";
33
+ this.token = config.token;
34
+ this.stack = config.stack;
35
+
36
+ // URL base configurável
37
+ this.baseUrl = config.baseUrl || "https://mkgplyz3tc.execute-api.us-east-1.amazonaws.com/lambdaUploadProducao";
38
+
39
+ // Endpoints configuráveis
40
+ this.endpoints = {
41
+ upload: config.endpoints?.upload || "/arquivo/upload",
42
+ recuperar: config.endpoints?.recuperar || "/arquivo/recuperar",
43
+ listar: config.endpoints?.listar || "/arquivo/listar",
44
+ ...config.endpoints
45
+ };
46
+
47
+ // URLs completas
48
+ this.urls = {
49
+ upload: `${this.baseUrl}${this.endpoints.upload}`,
50
+ recuperar: `${this.baseUrl}${this.endpoints.recuperar}`,
51
+ listar: `${this.baseUrl}${this.endpoints.listar}`
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Método estático para manter retrocompatibilidade com a assinatura antiga
57
+ * @deprecated Use o constructor com objeto de configuração
58
+ * @param {boolean} isProd - Define se está em ambiente de produção
59
+ * @param {string} token - Token de autorização
60
+ * @param {string} stack - Nome da stack
61
+ * @returns {PolgoUploadClient} Nova instância do cliente
62
+ */
63
+ static createLegacy(isProd, token, stack) {
64
+ console.warn('⚠️ PolgoUploadClient.createLegacy() está deprecated. Use o constructor com objeto de configuração.');
65
+ return new PolgoUploadClient({
66
+ isProd,
67
+ token,
68
+ stack
69
+ });
70
+ }
71
+
72
+ async recuperarArquivos(bucket, key) {
73
+ const queryParams = new URLSearchParams({
74
+ bucket,
75
+ key,
76
+ });
77
+
78
+ const finalUrl = `${this.urls.recuperar}?${queryParams.toString()}`;
79
+
80
+ try {
81
+ const response = await axios.get(finalUrl, {
82
+ headers: {
83
+ Authorization: `Bearer ${this.token}`,
84
+ },
85
+ });
86
+
87
+ return response.data;
88
+ } catch (error) {
89
+ console.error("Erro ao recuperar arquivo:", error.message);
90
+
91
+ throw new Error(`Falha ao recuperar o arquivo: ${error.message}`);
92
+ }
10
93
  }
11
94
 
12
95
  async listarArquivos(bucket, key) {
@@ -15,7 +98,7 @@ class PolgoUploadClient {
15
98
  key,
16
99
  });
17
100
 
18
- const finalUrl = `https://mkgplyz3tc.execute-api.us-east-1.amazonaws.com/lambdaUploadProducao/arquivo/listar?${queryParams.toString()}`;
101
+ const finalUrl = `${this.urls.listar}?${queryParams.toString()}`;
19
102
 
20
103
  try {
21
104
  const response = await axios.get(finalUrl, {
@@ -31,6 +114,41 @@ class PolgoUploadClient {
31
114
  }
32
115
  }
33
116
 
117
+ /**
118
+ * Faz upload de um arquivo para o bucket especificado
119
+ * @param {File|Buffer} bufferArquivo - O arquivo a ser enviado
120
+ * @param {string} bucket - Nome do bucket de destino
121
+ * @param {Object} options - Opções do upload
122
+ * @param {string} [options.diretorio] - Diretório de destino no bucket
123
+ * @param {string} [options.nomeArquivo] - Nome personalizado para o arquivo
124
+ * @param {Object} [options.otimizacao] - Parâmetros de otimização de imagem
125
+ * @param {number} [options.otimizacao.qualidade] - Qualidade da imagem (0-100, padrão: 85)
126
+ * @param {number} [options.otimizacao.largura] - Largura desejada em pixels
127
+ * @param {number} [options.otimizacao.altura] - Altura desejada em pixels
128
+ * @param {string} [options.otimizacao.formato] - Formato de saída (jpeg, png, webp)
129
+ * @param {number} [options.otimizacao.compressao] - Nível de compressão (0-9)
130
+ * @param {boolean} [options.otimizacao.manterProporcao] - Manter proporção ao redimensionar (padrão: true)
131
+ * @param {Function} [onProgress] - Callback para acompanhar progresso do upload
132
+ * @returns {Promise<Object>} Dados de resposta do upload
133
+ *
134
+ * @example
135
+ * // Upload simples
136
+ * await client.uploadFile(file, 'meu-bucket');
137
+ *
138
+ * @example
139
+ * // Upload com otimização de imagem
140
+ * await client.uploadFile(file, 'meu-bucket', {
141
+ * diretorio: 'imagens/perfil',
142
+ * nomeArquivo: 'avatar.jpg',
143
+ * otimizacao: {
144
+ * qualidade: 80,
145
+ * largura: 800,
146
+ * altura: 600,
147
+ * formato: 'webp',
148
+ * manterProporcao: true
149
+ * }
150
+ * }, (progress) => console.log(`Progress: ${progress}%`));
151
+ */
34
152
  async uploadFile(bufferArquivo, bucket, options = {}, onProgress) {
35
153
  const mimeType = bufferArquivo.type;
36
154
 
@@ -42,10 +160,25 @@ class PolgoUploadClient {
42
160
  });
43
161
 
44
162
  if (options.diretorio) queryParams.append("diretorio", options.diretorio);
45
- if (options.nomeArquivo)
46
- queryParams.append("nomeArquivo", options.nomeArquivo);
163
+ if (options.nomeArquivo) queryParams.append("nomeArquivo", options.nomeArquivo);
164
+
165
+ // Parâmetro de otimização simplificado conforme esperado pela lambda
166
+ if (options.otimizacao) {
167
+ const { formato } = options.otimizacao;
168
+ if (formato === 'avif') {
169
+ queryParams.append("otimizacao", "avif");
170
+ } else if (formato === 'webp') {
171
+ queryParams.append("otimizacao", "webp");
172
+ } else if (formato === 'none' || formato === false) {
173
+ queryParams.append("otimizacao", "false");
174
+ } else {
175
+ queryParams.append("otimizacao", "webp"); // padrão
176
+ }
177
+ } else {
178
+ queryParams.append("otimizacao", "webp"); // padrão quando não especificado
179
+ }
47
180
 
48
- const finalUrl = `${this.url}?${queryParams.toString()}`;
181
+ const finalUrl = `${this.urls.upload}?${queryParams.toString()}`;
49
182
  const form = new FormData();
50
183
  form.append("file", fileBlob, options.nomeArquivo || "uploaded_file");
51
184
  form.append("bucket", bucket);
@@ -75,4 +208,4 @@ class PolgoUploadClient {
75
208
  }
76
209
  }
77
210
 
78
- export { PolgoUploadClient };
211
+ export { PolgoUploadClient };