polgo-upload-kit 1.1.12 → 1.2.1

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