polgo-upload-kit 1.2.3 → 2.0.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.
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuracoes do cliente de upload
|
|
3
|
+
*/
|
|
4
|
+
export interface PolgoUploadClientConfig {
|
|
5
|
+
/** Define se esta em ambiente de producao */
|
|
6
|
+
isProd?: boolean;
|
|
7
|
+
/** Token de autorizacao Bearer */
|
|
8
|
+
token: string;
|
|
9
|
+
/** Nome da stack/aplicacao */
|
|
10
|
+
stack: string;
|
|
11
|
+
/** URL base personalizada para a API */
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
/** Timeout das requisicoes em ms (padrao: 30s) */
|
|
14
|
+
timeout?: number;
|
|
15
|
+
/** Endpoints personalizados */
|
|
16
|
+
endpoints?: EndpointsConfig;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Configuracao de endpoints personalizados
|
|
20
|
+
*/
|
|
21
|
+
export interface EndpointsConfig {
|
|
22
|
+
/** Endpoint de upload personalizado */
|
|
23
|
+
upload?: string;
|
|
24
|
+
/** Endpoint de recuperacao personalizado */
|
|
25
|
+
recuperar?: string;
|
|
26
|
+
/** Endpoint de listagem personalizado */
|
|
27
|
+
listar?: string;
|
|
28
|
+
[key: string]: string | undefined;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Opcoes para upload de arquivo
|
|
32
|
+
*/
|
|
33
|
+
export interface UploadOptions {
|
|
34
|
+
/** Diretorio de destino no bucket */
|
|
35
|
+
diretorio?: string;
|
|
36
|
+
/** Nome personalizado para o arquivo */
|
|
37
|
+
nomeArquivo?: string;
|
|
38
|
+
/**
|
|
39
|
+
* Otimizacao conforme a lambda espera:
|
|
40
|
+
* - false: desabilita otimizacao
|
|
41
|
+
* - "jpeg" | "webp" | "avif": formato desejado (padrao: "webp")
|
|
42
|
+
* - { formato }: compatibilidade com versoes antigas (aceita "none" para desabilitar)
|
|
43
|
+
*/
|
|
44
|
+
otimizacao?: false | "jpeg" | "webp" | "avif" | {
|
|
45
|
+
formato?: string;
|
|
46
|
+
};
|
|
47
|
+
/** Forca conversao mesmo se o arquivo resultante for maior que o original */
|
|
48
|
+
forcarConversao?: boolean;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Resultado do upload de arquivo
|
|
52
|
+
*/
|
|
53
|
+
export interface UploadResult {
|
|
54
|
+
/** ID unico do arquivo */
|
|
55
|
+
id: string;
|
|
56
|
+
/** URL do arquivo no bucket */
|
|
57
|
+
endereco: string;
|
|
58
|
+
/** Tamanho original do arquivo em bytes */
|
|
59
|
+
tamanhoOriginal: number;
|
|
60
|
+
/** Tamanho do arquivo apos otimizacao em bytes */
|
|
61
|
+
tamanhoOtimizado: number;
|
|
62
|
+
/** Indica se o arquivo foi otimizado */
|
|
63
|
+
otimizado: boolean;
|
|
64
|
+
/** Formato MIME original do arquivo */
|
|
65
|
+
formatoOriginal: string;
|
|
66
|
+
/** Formato MIME apos otimizacao */
|
|
67
|
+
formatoOtimizado: string;
|
|
68
|
+
/** Percentual de economia de espaco (pode ser negativo se forcar conversao) */
|
|
69
|
+
economiaPercentual: number;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Resultado da recuperacao de arquivo
|
|
73
|
+
*/
|
|
74
|
+
export interface RecuperarArquivoResult {
|
|
75
|
+
/** URL pre-assinada do arquivo */
|
|
76
|
+
url?: string;
|
|
77
|
+
/** Dados do arquivo */
|
|
78
|
+
[key: string]: unknown;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Item da listagem de arquivos
|
|
82
|
+
*/
|
|
83
|
+
export interface ArquivoListItem {
|
|
84
|
+
/** Chave do arquivo no bucket */
|
|
85
|
+
key: string;
|
|
86
|
+
/** Tamanho do arquivo em bytes */
|
|
87
|
+
size?: number;
|
|
88
|
+
/** Data da ultima modificacao */
|
|
89
|
+
lastModified?: string;
|
|
90
|
+
[key: string]: unknown;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Callback de progresso do upload
|
|
94
|
+
*/
|
|
95
|
+
export type ProgressCallback = (percentCompleted: number) => void;
|
|
96
|
+
/**
|
|
97
|
+
* Cliente para upload de arquivos para o servico Polgo
|
|
98
|
+
*/
|
|
99
|
+
declare class PolgoUploadClient {
|
|
100
|
+
private isProd;
|
|
101
|
+
private ambiente;
|
|
102
|
+
private token;
|
|
103
|
+
private stack;
|
|
104
|
+
private timeout;
|
|
105
|
+
private baseUrl;
|
|
106
|
+
private endpoints;
|
|
107
|
+
private urls;
|
|
108
|
+
/**
|
|
109
|
+
* Inicializa o cliente de upload
|
|
110
|
+
* @param config - Configuracoes do cliente
|
|
111
|
+
*/
|
|
112
|
+
constructor(config: PolgoUploadClientConfig);
|
|
113
|
+
/**
|
|
114
|
+
* Valida se o bucket foi informado
|
|
115
|
+
* @param bucket - Nome do bucket
|
|
116
|
+
*/
|
|
117
|
+
private _validarBucket;
|
|
118
|
+
/**
|
|
119
|
+
* Trata erros das requisicoes HTTP
|
|
120
|
+
* @param error - Erro capturado
|
|
121
|
+
* @param operacao - Nome da operacao que falhou
|
|
122
|
+
*/
|
|
123
|
+
private _handleError;
|
|
124
|
+
/**
|
|
125
|
+
* Recupera um arquivo do bucket especificado
|
|
126
|
+
* @param bucket - Nome do bucket
|
|
127
|
+
* @param key - Chave (caminho) do arquivo no bucket
|
|
128
|
+
* @returns Dados do arquivo recuperado
|
|
129
|
+
* @throws Se houver erro na requisicao ou arquivo nao encontrado
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* const arquivo = await client.recuperarArquivos('meu-bucket', 'imagens/avatar.jpg');
|
|
133
|
+
*/
|
|
134
|
+
recuperarArquivos(bucket: string, key: string): Promise<RecuperarArquivoResult>;
|
|
135
|
+
/**
|
|
136
|
+
* Lista arquivos de um diretorio no bucket
|
|
137
|
+
* @param bucket - Nome do bucket
|
|
138
|
+
* @param key - Chave (caminho) do diretorio no bucket
|
|
139
|
+
* @returns Lista de arquivos encontrados
|
|
140
|
+
* @throws Se houver erro na requisicao ou diretorio nao encontrado
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* const arquivos = await client.listarArquivos('meu-bucket', 'imagens/perfil');
|
|
144
|
+
*/
|
|
145
|
+
listarArquivos(bucket: string, key: string): Promise<ArquivoListItem[]>;
|
|
146
|
+
/**
|
|
147
|
+
* Faz upload de um arquivo para o bucket especificado
|
|
148
|
+
* @param bufferArquivo - O arquivo a ser enviado
|
|
149
|
+
* @param bucket - Nome do bucket de destino
|
|
150
|
+
* @param options - Opcoes do upload
|
|
151
|
+
* @param onProgress - Callback para acompanhar progresso do upload (recebe percentual 0-100)
|
|
152
|
+
* @returns Dados de resposta do upload
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* // Upload simples
|
|
156
|
+
* await client.uploadFile(file, 'meu-bucket');
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* // Upload com otimizacao de imagem
|
|
160
|
+
* await client.uploadFile(file, 'meu-bucket', {
|
|
161
|
+
* diretorio: 'imagens/perfil',
|
|
162
|
+
* nomeArquivo: 'avatar.jpg',
|
|
163
|
+
* otimizacao: 'webp'
|
|
164
|
+
* }, (progress) => console.log(`Progress: ${progress}%`));
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* // Upload com conversao forcada (mantem formato mesmo se maior)
|
|
168
|
+
* await client.uploadFile(file, 'meu-bucket', {
|
|
169
|
+
* otimizacao: 'avif',
|
|
170
|
+
* forcarConversao: true
|
|
171
|
+
* });
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* // Upload sem otimizacao
|
|
175
|
+
* await client.uploadFile(file, 'meu-bucket', {
|
|
176
|
+
* otimizacao: false
|
|
177
|
+
* });
|
|
178
|
+
*/
|
|
179
|
+
uploadFile(bufferArquivo: File | Blob, bucket: string, options?: UploadOptions, onProgress?: ProgressCallback): Promise<UploadResult>;
|
|
180
|
+
}
|
|
181
|
+
export { PolgoUploadClient };
|
|
182
|
+
export default PolgoUploadClient;
|
|
183
|
+
//# sourceMappingURL=polgoUploadClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"polgoUploadClient.d.ts","sourceRoot":"","sources":["../src/polgoUploadClient.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,6CAA6C;IAC7C,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,kCAAkC;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,8BAA8B;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,wCAAwC;IACxC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kDAAkD;IAClD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,+BAA+B;IAC/B,SAAS,CAAC,EAAE,eAAe,CAAC;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,uCAAuC;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CACnC;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,qCAAqC;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wCAAwC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACrE,6EAA6E;IAC7E,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,0BAA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AC,YAAY;IA2BpB;;;;;;;;;OASG;IACG,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,CAAC;IA4BrF;;;;;;;;;OASG;IACG,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IA4B7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACG,UAAU,CACd,aAAa,EAAE,IAAI,GAAG,IAAI,EAC1B,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,aAAkB,EAC3B,UAAU,CAAC,EAAE,gBAAgB,GAC5B,OAAO,CAAC,YAAY,CAAC;CAkEzB;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
/**
|
|
3
|
+
* Cliente para upload de arquivos para o servico Polgo
|
|
4
|
+
*/
|
|
5
|
+
class PolgoUploadClient {
|
|
6
|
+
/**
|
|
7
|
+
* Inicializa o cliente de upload
|
|
8
|
+
* @param config - Configuracoes do cliente
|
|
9
|
+
*/
|
|
10
|
+
constructor(config) {
|
|
11
|
+
// Validacao de parametros obrigatorios
|
|
12
|
+
if (!config.token) {
|
|
13
|
+
throw new Error("Token de autorizacao e obrigatorio");
|
|
14
|
+
}
|
|
15
|
+
if (!config.stack) {
|
|
16
|
+
throw new Error("Stack e obrigatoria");
|
|
17
|
+
}
|
|
18
|
+
// Configuracoes principais
|
|
19
|
+
this.isProd = config.isProd || false;
|
|
20
|
+
this.ambiente = this.isProd ? "producao" : "dev";
|
|
21
|
+
this.token = config.token;
|
|
22
|
+
this.stack = config.stack;
|
|
23
|
+
this.timeout = config.timeout || 30000;
|
|
24
|
+
// URL base configuravel
|
|
25
|
+
this.baseUrl = config.baseUrl || "https://uploadws.polgo.com.br";
|
|
26
|
+
// Endpoints configuraveis
|
|
27
|
+
this.endpoints = {
|
|
28
|
+
upload: config.endpoints?.upload || "/arquivo/upload",
|
|
29
|
+
recuperar: config.endpoints?.recuperar || "/arquivo/recuperar",
|
|
30
|
+
listar: config.endpoints?.listar || "/arquivo/listar",
|
|
31
|
+
...config.endpoints
|
|
32
|
+
};
|
|
33
|
+
// URLs completas
|
|
34
|
+
this.urls = {
|
|
35
|
+
upload: `${this.baseUrl}${this.endpoints.upload}`,
|
|
36
|
+
recuperar: `${this.baseUrl}${this.endpoints.recuperar}`,
|
|
37
|
+
listar: `${this.baseUrl}${this.endpoints.listar}`
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Valida se o bucket foi informado
|
|
42
|
+
* @param bucket - Nome do bucket
|
|
43
|
+
*/
|
|
44
|
+
_validarBucket(bucket) {
|
|
45
|
+
if (!bucket || typeof bucket !== "string" || bucket.trim() === "") {
|
|
46
|
+
throw new Error("Bucket e obrigatorio");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Trata erros das requisicoes HTTP
|
|
51
|
+
* @param error - Erro capturado
|
|
52
|
+
* @param operacao - Nome da operacao que falhou
|
|
53
|
+
*/
|
|
54
|
+
_handleError(error, operacao) {
|
|
55
|
+
if (error.response) {
|
|
56
|
+
const status = error.response.status;
|
|
57
|
+
const data = error.response.data;
|
|
58
|
+
if (status === 401) {
|
|
59
|
+
throw new Error("Nao autorizado. Verifique seu token de acesso.");
|
|
60
|
+
}
|
|
61
|
+
else if (status === 400) {
|
|
62
|
+
throw new Error(data?.message || "Requisicao invalida. Verifique os parametros enviados.");
|
|
63
|
+
}
|
|
64
|
+
else if (status === 404) {
|
|
65
|
+
throw new Error(data?.message || "Recurso nao encontrado.");
|
|
66
|
+
}
|
|
67
|
+
else if (status === 413) {
|
|
68
|
+
throw new Error("Arquivo muito grande. Tamanho maximo excedido.");
|
|
69
|
+
}
|
|
70
|
+
else if (status >= 500) {
|
|
71
|
+
throw new Error("Erro interno do servidor. Tente novamente mais tarde.");
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
throw new Error(data?.message || `Falha ao ${operacao}: ${error.message}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
else if (error.code === "ECONNABORTED") {
|
|
78
|
+
throw new Error(`Timeout: a requisicao excedeu o tempo limite de ${this.timeout}ms.`);
|
|
79
|
+
}
|
|
80
|
+
else if (error.request) {
|
|
81
|
+
throw new Error("Nao foi possivel conectar ao servidor. Verifique sua conexao.");
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
throw new Error(`Falha ao ${operacao}: ${error.message}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Recupera um arquivo do bucket especificado
|
|
89
|
+
* @param bucket - Nome do bucket
|
|
90
|
+
* @param key - Chave (caminho) do arquivo no bucket
|
|
91
|
+
* @returns Dados do arquivo recuperado
|
|
92
|
+
* @throws Se houver erro na requisicao ou arquivo nao encontrado
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* const arquivo = await client.recuperarArquivos('meu-bucket', 'imagens/avatar.jpg');
|
|
96
|
+
*/
|
|
97
|
+
async recuperarArquivos(bucket, key) {
|
|
98
|
+
this._validarBucket(bucket);
|
|
99
|
+
if (!key || typeof key !== "string" || key.trim() === "") {
|
|
100
|
+
throw new Error("Key e obrigatoria");
|
|
101
|
+
}
|
|
102
|
+
const queryParams = new URLSearchParams({
|
|
103
|
+
bucket,
|
|
104
|
+
key,
|
|
105
|
+
});
|
|
106
|
+
const finalUrl = `${this.urls.recuperar}?${queryParams.toString()}`;
|
|
107
|
+
try {
|
|
108
|
+
const response = await axios.get(finalUrl, {
|
|
109
|
+
headers: {
|
|
110
|
+
Authorization: `Bearer ${this.token}`,
|
|
111
|
+
},
|
|
112
|
+
timeout: this.timeout,
|
|
113
|
+
});
|
|
114
|
+
return response.data;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
this._handleError(error, "recuperar arquivo");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Lista arquivos de um diretorio no bucket
|
|
122
|
+
* @param bucket - Nome do bucket
|
|
123
|
+
* @param key - Chave (caminho) do diretorio no bucket
|
|
124
|
+
* @returns Lista de arquivos encontrados
|
|
125
|
+
* @throws Se houver erro na requisicao ou diretorio nao encontrado
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* const arquivos = await client.listarArquivos('meu-bucket', 'imagens/perfil');
|
|
129
|
+
*/
|
|
130
|
+
async listarArquivos(bucket, key) {
|
|
131
|
+
this._validarBucket(bucket);
|
|
132
|
+
if (!key || typeof key !== "string" || key.trim() === "") {
|
|
133
|
+
throw new Error("Key e obrigatoria");
|
|
134
|
+
}
|
|
135
|
+
const queryParams = new URLSearchParams({
|
|
136
|
+
bucket,
|
|
137
|
+
key,
|
|
138
|
+
});
|
|
139
|
+
const finalUrl = `${this.urls.listar}?${queryParams.toString()}`;
|
|
140
|
+
try {
|
|
141
|
+
const response = await axios.get(finalUrl, {
|
|
142
|
+
headers: {
|
|
143
|
+
Authorization: `Bearer ${this.token}`,
|
|
144
|
+
},
|
|
145
|
+
timeout: this.timeout,
|
|
146
|
+
});
|
|
147
|
+
return response.data.arquivos || [];
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
this._handleError(error, "listar arquivos");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Faz upload de um arquivo para o bucket especificado
|
|
155
|
+
* @param bufferArquivo - O arquivo a ser enviado
|
|
156
|
+
* @param bucket - Nome do bucket de destino
|
|
157
|
+
* @param options - Opcoes do upload
|
|
158
|
+
* @param onProgress - Callback para acompanhar progresso do upload (recebe percentual 0-100)
|
|
159
|
+
* @returns Dados de resposta do upload
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* // Upload simples
|
|
163
|
+
* await client.uploadFile(file, 'meu-bucket');
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* // Upload com otimizacao de imagem
|
|
167
|
+
* await client.uploadFile(file, 'meu-bucket', {
|
|
168
|
+
* diretorio: 'imagens/perfil',
|
|
169
|
+
* nomeArquivo: 'avatar.jpg',
|
|
170
|
+
* otimizacao: 'webp'
|
|
171
|
+
* }, (progress) => console.log(`Progress: ${progress}%`));
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* // Upload com conversao forcada (mantem formato mesmo se maior)
|
|
175
|
+
* await client.uploadFile(file, 'meu-bucket', {
|
|
176
|
+
* otimizacao: 'avif',
|
|
177
|
+
* forcarConversao: true
|
|
178
|
+
* });
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* // Upload sem otimizacao
|
|
182
|
+
* await client.uploadFile(file, 'meu-bucket', {
|
|
183
|
+
* otimizacao: false
|
|
184
|
+
* });
|
|
185
|
+
*/
|
|
186
|
+
async uploadFile(bufferArquivo, bucket, options = {}, onProgress) {
|
|
187
|
+
this._validarBucket(bucket);
|
|
188
|
+
if (!bufferArquivo) {
|
|
189
|
+
throw new Error("Arquivo e obrigatorio");
|
|
190
|
+
}
|
|
191
|
+
const mimeType = bufferArquivo.type;
|
|
192
|
+
const fileBlob = new Blob([bufferArquivo], { type: mimeType });
|
|
193
|
+
const queryParams = new URLSearchParams({
|
|
194
|
+
ambiente: this.ambiente,
|
|
195
|
+
stack: this.stack,
|
|
196
|
+
});
|
|
197
|
+
if (options.diretorio)
|
|
198
|
+
queryParams.append("diretorio", options.diretorio);
|
|
199
|
+
if (options.nomeArquivo)
|
|
200
|
+
queryParams.append("nomeArquivo", options.nomeArquivo);
|
|
201
|
+
if (options.forcarConversao === true) {
|
|
202
|
+
queryParams.append("forcarConversao", "true");
|
|
203
|
+
}
|
|
204
|
+
// Parametro de otimizacao conforme a lambda espera (false|0|jpeg|webp|avif; padrao: webp)
|
|
205
|
+
const normalizarOtimizacao = (otimizacao) => {
|
|
206
|
+
if (otimizacao === undefined || otimizacao === null)
|
|
207
|
+
return "webp";
|
|
208
|
+
if (otimizacao === false)
|
|
209
|
+
return "false";
|
|
210
|
+
// Compatibilidade com a forma antiga: { formato: 'webp' }
|
|
211
|
+
if (typeof otimizacao === "object") {
|
|
212
|
+
const formato = otimizacao?.formato;
|
|
213
|
+
if (formato === undefined || formato === null)
|
|
214
|
+
return "webp";
|
|
215
|
+
if (formato === "false" || formato === "0" || formato === "none")
|
|
216
|
+
return "false";
|
|
217
|
+
if (formato === "jpg")
|
|
218
|
+
return "jpeg";
|
|
219
|
+
if (formato === "jpeg" || formato === "webp" || formato === "avif")
|
|
220
|
+
return formato;
|
|
221
|
+
return "webp";
|
|
222
|
+
}
|
|
223
|
+
if (otimizacao === "jpeg" || otimizacao === "webp" || otimizacao === "avif")
|
|
224
|
+
return otimizacao;
|
|
225
|
+
return "webp";
|
|
226
|
+
};
|
|
227
|
+
queryParams.append("otimizacao", normalizarOtimizacao(options.otimizacao));
|
|
228
|
+
const finalUrl = `${this.urls.upload}?${queryParams.toString()}`;
|
|
229
|
+
const form = new FormData();
|
|
230
|
+
form.append("file", fileBlob, options.nomeArquivo || "uploaded_file");
|
|
231
|
+
form.append("bucket", bucket);
|
|
232
|
+
try {
|
|
233
|
+
const response = await axios.post(finalUrl, form, {
|
|
234
|
+
headers: {
|
|
235
|
+
Authorization: `Bearer ${this.token}`,
|
|
236
|
+
},
|
|
237
|
+
timeout: this.timeout,
|
|
238
|
+
onUploadProgress: (progressEvent) => {
|
|
239
|
+
if (typeof onProgress === "function" && progressEvent.total) {
|
|
240
|
+
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
|
|
241
|
+
onProgress(percentCompleted);
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
return response.data;
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
this._handleError(error, "fazer upload");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
export { PolgoUploadClient };
|
|
253
|
+
export default PolgoUploadClient;
|
|
254
|
+
//# sourceMappingURL=polgoUploadClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"polgoUploadClient.js","sourceRoot":"","sources":["../src/polgoUploadClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAyC,MAAM,OAAO,CAAC;AA+G9D;;GAEG;AACH,MAAM,iBAAiB;IAUrB;;;OAGG;IACH,YAAY,MAA+B;QACzC,uCAAuC;QACvC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;QACzC,CAAC;QAED,2BAA2B;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,KAAK,CAAC;QACrC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC;QACjD,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,KAAK,CAAC;QAEvC,wBAAwB;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,+BAA+B,CAAC;QAEjE,0BAA0B;QAC1B,IAAI,CAAC,SAAS,GAAG;YACf,MAAM,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,IAAI,iBAAiB;YACrD,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,SAAS,IAAI,oBAAoB;YAC9D,MAAM,EAAE,MAAM,CA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KAAK,EAAE,CAAC;wBAC5D,MAAM,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,aAAa,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;wBACxF,UAAU,CAAC,gBAAgB,CAAC,CAAC;oBAC/B,CAAC;gBACH,CAAC;aACF,CAAC,CAAC;YAEH,OAAO,QAAQ,CAAC,IAAI,CAAC;QACvB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,YAAY,CAAC,KAAyC,EAAE,cAAc,CAAC,CAAC;QAC/E,CAAC;IACH,CAAC;CACF;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,22 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polgo-upload-kit",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"main": "
|
|
5
|
+
"main": "./dist/polgoUploadClient.js",
|
|
6
|
+
"types": "./dist/polgoUploadClient.d.ts",
|
|
6
7
|
"exports": {
|
|
7
|
-
".":
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/polgoUploadClient.d.ts",
|
|
10
|
+
"import": "./dist/polgoUploadClient.js"
|
|
11
|
+
},
|
|
12
|
+
"./src/polgoUploadClient": {
|
|
13
|
+
"types": "./dist/polgoUploadClient.d.ts",
|
|
14
|
+
"import": "./dist/polgoUploadClient.js"
|
|
15
|
+
},
|
|
16
|
+
"./src/polgoUploadClient.js": {
|
|
17
|
+
"types": "./dist/polgoUploadClient.d.ts",
|
|
18
|
+
"import": "./dist/polgoUploadClient.js"
|
|
19
|
+
}
|
|
8
20
|
},
|
|
9
21
|
"files": [
|
|
22
|
+
"dist",
|
|
10
23
|
"src"
|
|
11
24
|
],
|
|
12
25
|
"scripts": {
|
|
13
|
-
"build": "
|
|
26
|
+
"build": "tsc",
|
|
27
|
+
"prepublishOnly": "npm run build"
|
|
14
28
|
},
|
|
15
29
|
"keywords": [
|
|
16
30
|
"upload",
|
|
17
31
|
"s3",
|
|
18
32
|
"polgo",
|
|
19
|
-
"file-upload"
|
|
33
|
+
"file-upload",
|
|
34
|
+
"typescript"
|
|
20
35
|
],
|
|
21
36
|
"author": "Grupo NSC",
|
|
22
37
|
"license": "ISC",
|
|
@@ -30,8 +45,10 @@
|
|
|
30
45
|
},
|
|
31
46
|
"homepage": "https://github.com/Grupo-NSC/polgo-upload-kit#readme",
|
|
32
47
|
"dependencies": {
|
|
33
|
-
"axios": "^1.7.7"
|
|
34
|
-
|
|
35
|
-
|
|
48
|
+
"axios": "^1.7.7"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/node": "^22.10.5",
|
|
52
|
+
"typescript": "^5.7.3"
|
|
36
53
|
}
|
|
37
54
|
}
|
|
@@ -1,42 +1,132 @@
|
|
|
1
|
-
import axios from "axios";
|
|
1
|
+
import axios, { AxiosError, AxiosProgressEvent } from "axios";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Configuracoes do cliente de upload
|
|
5
|
+
*/
|
|
6
|
+
export interface PolgoUploadClientConfig {
|
|
7
|
+
/** Define se esta em ambiente de producao */
|
|
8
|
+
isProd?: boolean;
|
|
9
|
+
/** Token de autorizacao Bearer */
|
|
10
|
+
token: string;
|
|
11
|
+
/** Nome da stack/aplicacao */
|
|
12
|
+
stack: string;
|
|
13
|
+
/** URL base personalizada para a API */
|
|
14
|
+
baseUrl?: string;
|
|
15
|
+
/** Timeout das requisicoes em ms (padrao: 30s) */
|
|
16
|
+
timeout?: number;
|
|
17
|
+
/** Endpoints personalizados */
|
|
18
|
+
endpoints?: EndpointsConfig;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Configuracao de endpoints personalizados
|
|
23
|
+
*/
|
|
24
|
+
export interface EndpointsConfig {
|
|
25
|
+
/** Endpoint de upload personalizado */
|
|
26
|
+
upload?: string;
|
|
27
|
+
/** Endpoint de recuperacao personalizado */
|
|
28
|
+
recuperar?: string;
|
|
29
|
+
/** Endpoint de listagem personalizado */
|
|
30
|
+
listar?: string;
|
|
31
|
+
[key: string]: string | undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Opcoes para upload de arquivo
|
|
36
|
+
*/
|
|
37
|
+
export interface UploadOptions {
|
|
38
|
+
/** Diretorio de destino no bucket */
|
|
39
|
+
diretorio?: string;
|
|
40
|
+
/** Nome personalizado para o arquivo */
|
|
41
|
+
nomeArquivo?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Otimizacao conforme a lambda espera:
|
|
44
|
+
* - false: desabilita otimizacao
|
|
45
|
+
* - "jpeg" | "webp" | "avif": formato desejado (padrao: "webp")
|
|
46
|
+
* - { formato }: compatibilidade com versoes antigas (aceita "none" para desabilitar)
|
|
47
|
+
*/
|
|
48
|
+
otimizacao?: false | "jpeg" | "webp" | "avif" | { formato?: string };
|
|
49
|
+
/** Forca conversao mesmo se o arquivo resultante for maior que o original */
|
|
50
|
+
forcarConversao?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Resultado do upload de arquivo
|
|
55
|
+
*/
|
|
56
|
+
export interface UploadResult {
|
|
57
|
+
/** ID unico do arquivo */
|
|
58
|
+
id: string;
|
|
59
|
+
/** URL do arquivo no bucket */
|
|
60
|
+
endereco: string;
|
|
61
|
+
/** Tamanho original do arquivo em bytes */
|
|
62
|
+
tamanhoOriginal: number;
|
|
63
|
+
/** Tamanho do arquivo apos otimizacao em bytes */
|
|
64
|
+
tamanhoOtimizado: number;
|
|
65
|
+
/** Indica se o arquivo foi otimizado */
|
|
66
|
+
otimizado: boolean;
|
|
67
|
+
/** Formato MIME original do arquivo */
|
|
68
|
+
formatoOriginal: string;
|
|
69
|
+
/** Formato MIME apos otimizacao */
|
|
70
|
+
formatoOtimizado: string;
|
|
71
|
+
/** Percentual de economia de espaco (pode ser negativo se forcar conversao) */
|
|
72
|
+
economiaPercentual: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Resultado da recuperacao de arquivo
|
|
77
|
+
*/
|
|
78
|
+
export interface RecuperarArquivoResult {
|
|
79
|
+
/** URL pre-assinada do arquivo */
|
|
80
|
+
url?: string;
|
|
81
|
+
/** Dados do arquivo */
|
|
82
|
+
[key: string]: unknown;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Item da listagem de arquivos
|
|
87
|
+
*/
|
|
88
|
+
export interface ArquivoListItem {
|
|
89
|
+
/** Chave do arquivo no bucket */
|
|
90
|
+
key: string;
|
|
91
|
+
/** Tamanho do arquivo em bytes */
|
|
92
|
+
size?: number;
|
|
93
|
+
/** Data da ultima modificacao */
|
|
94
|
+
lastModified?: string;
|
|
95
|
+
[key: string]: unknown;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Callback de progresso do upload
|
|
100
|
+
*/
|
|
101
|
+
export type ProgressCallback = (percentCompleted: number) => void;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* URLs internas do cliente
|
|
105
|
+
*/
|
|
106
|
+
interface ClientUrls {
|
|
107
|
+
upload: string;
|
|
108
|
+
recuperar: string;
|
|
109
|
+
listar: string;
|
|
110
|
+
}
|
|
2
111
|
|
|
3
112
|
/**
|
|
4
113
|
* Cliente para upload de arquivos para o servico Polgo
|
|
5
|
-
* @class PolgoUploadClient
|
|
6
114
|
*/
|
|
7
115
|
class PolgoUploadClient {
|
|
116
|
+
private isProd: boolean;
|
|
117
|
+
private ambiente: "producao" | "dev";
|
|
118
|
+
private token: string;
|
|
119
|
+
private stack: string;
|
|
120
|
+
private timeout: number;
|
|
121
|
+
private baseUrl: string;
|
|
122
|
+
private endpoints: Required<Pick<EndpointsConfig, "upload" | "recuperar" | "listar">> & EndpointsConfig;
|
|
123
|
+
private urls: ClientUrls;
|
|
124
|
+
|
|
8
125
|
/**
|
|
9
126
|
* Inicializa o cliente de upload
|
|
10
|
-
* @param
|
|
11
|
-
* @param {boolean} [configOrIsProd.isProd=false] - Define se esta em ambiente de producao
|
|
12
|
-
* @param {string} configOrIsProd.token - Token de autorizacao Bearer
|
|
13
|
-
* @param {string} configOrIsProd.stack - Nome da stack/aplicacao
|
|
14
|
-
* @param {string} [configOrIsProd.baseUrl] - URL base personalizada para a API
|
|
15
|
-
* @param {number} [configOrIsProd.timeout=30000] - Timeout das requisicoes em ms (padrao: 30s)
|
|
16
|
-
* @param {Object} [configOrIsProd.endpoints] - Endpoints personalizados
|
|
17
|
-
* @param {string} [configOrIsProd.endpoints.upload] - Endpoint de upload personalizado
|
|
18
|
-
* @param {string} [configOrIsProd.endpoints.recuperar] - Endpoint de recuperacao personalizado
|
|
19
|
-
* @param {string} [configOrIsProd.endpoints.listar] - Endpoint de listagem personalizado
|
|
20
|
-
* @param {string} [token] - Token de autorizacao (usado na assinatura antiga)
|
|
21
|
-
* @param {string} [stack] - Nome da stack (usado na assinatura antiga)
|
|
127
|
+
* @param config - Configuracoes do cliente
|
|
22
128
|
*/
|
|
23
|
-
constructor(
|
|
24
|
-
let config;
|
|
25
|
-
|
|
26
|
-
// Verifica se esta 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("Aviso: a assinatura PolgoUploadClient(isProd, token, stack) esta 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
|
-
|
|
129
|
+
constructor(config: PolgoUploadClientConfig) {
|
|
40
130
|
// Validacao de parametros obrigatorios
|
|
41
131
|
if (!config.token) {
|
|
42
132
|
throw new Error("Token de autorizacao e obrigatorio");
|
|
@@ -53,7 +143,7 @@ class PolgoUploadClient {
|
|
|
53
143
|
this.timeout = config.timeout || 30000;
|
|
54
144
|
|
|
55
145
|
// URL base configuravel
|
|
56
|
-
this.baseUrl = config.baseUrl || "https://
|
|
146
|
+
this.baseUrl = config.baseUrl || "https://uploadws.polgo.com.br";
|
|
57
147
|
|
|
58
148
|
// Endpoints configuraveis
|
|
59
149
|
this.endpoints = {
|
|
@@ -73,10 +163,9 @@ class PolgoUploadClient {
|
|
|
73
163
|
|
|
74
164
|
/**
|
|
75
165
|
* Valida se o bucket foi informado
|
|
76
|
-
* @param
|
|
77
|
-
* @private
|
|
166
|
+
* @param bucket - Nome do bucket
|
|
78
167
|
*/
|
|
79
|
-
_validarBucket(bucket) {
|
|
168
|
+
private _validarBucket(bucket: string): void {
|
|
80
169
|
if (!bucket || typeof bucket !== "string" || bucket.trim() === "") {
|
|
81
170
|
throw new Error("Bucket e obrigatorio");
|
|
82
171
|
}
|
|
@@ -84,11 +173,10 @@ class PolgoUploadClient {
|
|
|
84
173
|
|
|
85
174
|
/**
|
|
86
175
|
* Trata erros das requisicoes HTTP
|
|
87
|
-
* @param
|
|
88
|
-
* @param
|
|
89
|
-
* @private
|
|
176
|
+
* @param error - Erro capturado
|
|
177
|
+
* @param operacao - Nome da operacao que falhou
|
|
90
178
|
*/
|
|
91
|
-
_handleError(error
|
|
179
|
+
private _handleError(error: AxiosError<{ message?: string }>, operacao: string): never {
|
|
92
180
|
if (error.response) {
|
|
93
181
|
const status = error.response.status;
|
|
94
182
|
const data = error.response.data;
|
|
@@ -117,15 +205,15 @@ class PolgoUploadClient {
|
|
|
117
205
|
|
|
118
206
|
/**
|
|
119
207
|
* Recupera um arquivo do bucket especificado
|
|
120
|
-
* @param
|
|
121
|
-
* @param
|
|
122
|
-
* @returns
|
|
123
|
-
* @throws
|
|
208
|
+
* @param bucket - Nome do bucket
|
|
209
|
+
* @param key - Chave (caminho) do arquivo no bucket
|
|
210
|
+
* @returns Dados do arquivo recuperado
|
|
211
|
+
* @throws Se houver erro na requisicao ou arquivo nao encontrado
|
|
124
212
|
*
|
|
125
213
|
* @example
|
|
126
214
|
* const arquivo = await client.recuperarArquivos('meu-bucket', 'imagens/avatar.jpg');
|
|
127
215
|
*/
|
|
128
|
-
async recuperarArquivos(bucket, key) {
|
|
216
|
+
async recuperarArquivos(bucket: string, key: string): Promise<RecuperarArquivoResult> {
|
|
129
217
|
this._validarBucket(bucket);
|
|
130
218
|
|
|
131
219
|
if (!key || typeof key !== "string" || key.trim() === "") {
|
|
@@ -140,7 +228,7 @@ class PolgoUploadClient {
|
|
|
140
228
|
const finalUrl = `${this.urls.recuperar}?${queryParams.toString()}`;
|
|
141
229
|
|
|
142
230
|
try {
|
|
143
|
-
const response = await axios.get(finalUrl, {
|
|
231
|
+
const response = await axios.get<RecuperarArquivoResult>(finalUrl, {
|
|
144
232
|
headers: {
|
|
145
233
|
Authorization: `Bearer ${this.token}`,
|
|
146
234
|
},
|
|
@@ -149,21 +237,21 @@ class PolgoUploadClient {
|
|
|
149
237
|
|
|
150
238
|
return response.data;
|
|
151
239
|
} catch (error) {
|
|
152
|
-
this._handleError(error
|
|
240
|
+
this._handleError(error as AxiosError<{ message?: string }>, "recuperar arquivo");
|
|
153
241
|
}
|
|
154
242
|
}
|
|
155
243
|
|
|
156
244
|
/**
|
|
157
245
|
* Lista arquivos de um diretorio no bucket
|
|
158
|
-
* @param
|
|
159
|
-
* @param
|
|
160
|
-
* @returns
|
|
161
|
-
* @throws
|
|
246
|
+
* @param bucket - Nome do bucket
|
|
247
|
+
* @param key - Chave (caminho) do diretorio no bucket
|
|
248
|
+
* @returns Lista de arquivos encontrados
|
|
249
|
+
* @throws Se houver erro na requisicao ou diretorio nao encontrado
|
|
162
250
|
*
|
|
163
251
|
* @example
|
|
164
252
|
* const arquivos = await client.listarArquivos('meu-bucket', 'imagens/perfil');
|
|
165
253
|
*/
|
|
166
|
-
async listarArquivos(bucket, key) {
|
|
254
|
+
async listarArquivos(bucket: string, key: string): Promise<ArquivoListItem[]> {
|
|
167
255
|
this._validarBucket(bucket);
|
|
168
256
|
|
|
169
257
|
if (!key || typeof key !== "string" || key.trim() === "") {
|
|
@@ -178,7 +266,7 @@ class PolgoUploadClient {
|
|
|
178
266
|
const finalUrl = `${this.urls.listar}?${queryParams.toString()}`;
|
|
179
267
|
|
|
180
268
|
try {
|
|
181
|
-
const response = await axios.get(finalUrl, {
|
|
269
|
+
const response = await axios.get<{ arquivos?: ArquivoListItem[] }>(finalUrl, {
|
|
182
270
|
headers: {
|
|
183
271
|
Authorization: `Bearer ${this.token}`,
|
|
184
272
|
},
|
|
@@ -187,32 +275,17 @@ class PolgoUploadClient {
|
|
|
187
275
|
|
|
188
276
|
return response.data.arquivos || [];
|
|
189
277
|
} catch (error) {
|
|
190
|
-
this._handleError(error
|
|
278
|
+
this._handleError(error as AxiosError<{ message?: string }>, "listar arquivos");
|
|
191
279
|
}
|
|
192
280
|
}
|
|
193
281
|
|
|
194
282
|
/**
|
|
195
283
|
* Faz upload de um arquivo para o bucket especificado
|
|
196
|
-
* @param
|
|
197
|
-
* @param
|
|
198
|
-
* @param
|
|
199
|
-
* @param
|
|
200
|
-
* @
|
|
201
|
-
* @param {false|"jpeg"|"webp"|"avif"|Object} [options.otimizacao] - Otimizacao conforme a lambda espera:
|
|
202
|
-
* - false: desabilita otimizacao
|
|
203
|
-
* - "jpeg" | "webp" | "avif": formato desejado (padrao: "webp")
|
|
204
|
-
* - { formato }: compatibilidade com versoes antigas (aceita "none" para desabilitar)
|
|
205
|
-
* @param {boolean} [options.forcarConversao=false] - Forca conversao mesmo se o arquivo resultante for maior que o original
|
|
206
|
-
* @param {Function} [onProgress] - Callback para acompanhar progresso do upload (recebe percentual 0-100)
|
|
207
|
-
* @returns {Promise<Object>} Dados de resposta do upload contendo:
|
|
208
|
-
* - {string} id - ID unico do arquivo
|
|
209
|
-
* - {string} endereco - URL do arquivo no bucket
|
|
210
|
-
* - {number} tamanhoOriginal - Tamanho original do arquivo em bytes
|
|
211
|
-
* - {number} tamanhoOtimizado - Tamanho do arquivo apos otimizacao em bytes
|
|
212
|
-
* - {boolean} otimizado - Indica se o arquivo foi otimizado
|
|
213
|
-
* - {string} formatoOriginal - Formato MIME original do arquivo
|
|
214
|
-
* - {string} formatoOtimizado - Formato MIME apos otimizacao
|
|
215
|
-
* - {number} economiaPercentual - Percentual de economia de espaco (pode ser negativo se forcar conversao)
|
|
284
|
+
* @param bufferArquivo - O arquivo a ser enviado
|
|
285
|
+
* @param bucket - Nome do bucket de destino
|
|
286
|
+
* @param options - Opcoes do upload
|
|
287
|
+
* @param onProgress - Callback para acompanhar progresso do upload (recebe percentual 0-100)
|
|
288
|
+
* @returns Dados de resposta do upload
|
|
216
289
|
*
|
|
217
290
|
* @example
|
|
218
291
|
* // Upload simples
|
|
@@ -238,14 +311,13 @@ class PolgoUploadClient {
|
|
|
238
311
|
* await client.uploadFile(file, 'meu-bucket', {
|
|
239
312
|
* otimizacao: false
|
|
240
313
|
* });
|
|
241
|
-
*
|
|
242
|
-
* @example
|
|
243
|
-
* // Upload com compatibilidade de formato antigo
|
|
244
|
-
* await client.uploadFile(file, 'meu-bucket', {
|
|
245
|
-
* otimizacao: { formato: 'webp' }
|
|
246
|
-
* });
|
|
247
314
|
*/
|
|
248
|
-
async uploadFile(
|
|
315
|
+
async uploadFile(
|
|
316
|
+
bufferArquivo: File | Blob,
|
|
317
|
+
bucket: string,
|
|
318
|
+
options: UploadOptions = {},
|
|
319
|
+
onProgress?: ProgressCallback
|
|
320
|
+
): Promise<UploadResult> {
|
|
249
321
|
this._validarBucket(bucket);
|
|
250
322
|
|
|
251
323
|
if (!bufferArquivo) {
|
|
@@ -262,28 +334,25 @@ class PolgoUploadClient {
|
|
|
262
334
|
|
|
263
335
|
if (options.diretorio) queryParams.append("diretorio", options.diretorio);
|
|
264
336
|
if (options.nomeArquivo) queryParams.append("nomeArquivo", options.nomeArquivo);
|
|
265
|
-
if (options.forcarConversao === true
|
|
337
|
+
if (options.forcarConversao === true) {
|
|
266
338
|
queryParams.append("forcarConversao", "true");
|
|
267
339
|
}
|
|
268
340
|
|
|
269
341
|
// Parametro de otimizacao conforme a lambda espera (false|0|jpeg|webp|avif; padrao: webp)
|
|
270
|
-
const normalizarOtimizacao = (otimizacao) => {
|
|
342
|
+
const normalizarOtimizacao = (otimizacao: UploadOptions["otimizacao"]): string => {
|
|
271
343
|
if (otimizacao === undefined || otimizacao === null) return "webp";
|
|
272
|
-
if (otimizacao === false
|
|
344
|
+
if (otimizacao === false) return "false";
|
|
273
345
|
|
|
274
346
|
// Compatibilidade com a forma antiga: { formato: 'webp' }
|
|
275
347
|
if (typeof otimizacao === "object") {
|
|
276
348
|
const formato = otimizacao?.formato;
|
|
277
349
|
if (formato === undefined || formato === null) return "webp";
|
|
278
|
-
if (formato ===
|
|
350
|
+
if (formato === "false" || formato === "0" || formato === "none") return "false";
|
|
279
351
|
if (formato === "jpg") return "jpeg";
|
|
280
352
|
if (formato === "jpeg" || formato === "webp" || formato === "avif") return formato;
|
|
281
353
|
return "webp";
|
|
282
354
|
}
|
|
283
355
|
|
|
284
|
-
if (otimizacao === "false") return "false";
|
|
285
|
-
if (otimizacao === "none") return "false";
|
|
286
|
-
if (otimizacao === "jpg") return "jpeg";
|
|
287
356
|
if (otimizacao === "jpeg" || otimizacao === "webp" || otimizacao === "avif") return otimizacao;
|
|
288
357
|
return "webp";
|
|
289
358
|
};
|
|
@@ -296,12 +365,12 @@ class PolgoUploadClient {
|
|
|
296
365
|
form.append("bucket", bucket);
|
|
297
366
|
|
|
298
367
|
try {
|
|
299
|
-
const response = await axios.post(finalUrl, form, {
|
|
368
|
+
const response = await axios.post<UploadResult>(finalUrl, form, {
|
|
300
369
|
headers: {
|
|
301
370
|
Authorization: `Bearer ${this.token}`,
|
|
302
371
|
},
|
|
303
372
|
timeout: this.timeout,
|
|
304
|
-
onUploadProgress: (progressEvent) => {
|
|
373
|
+
onUploadProgress: (progressEvent: AxiosProgressEvent) => {
|
|
305
374
|
if (typeof onProgress === "function" && progressEvent.total) {
|
|
306
375
|
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
|
|
307
376
|
onProgress(percentCompleted);
|
|
@@ -311,9 +380,11 @@ class PolgoUploadClient {
|
|
|
311
380
|
|
|
312
381
|
return response.data;
|
|
313
382
|
} catch (error) {
|
|
314
|
-
this._handleError(error
|
|
383
|
+
this._handleError(error as AxiosError<{ message?: string }>, "fazer upload");
|
|
315
384
|
}
|
|
316
385
|
}
|
|
317
386
|
}
|
|
318
387
|
|
|
319
388
|
export { PolgoUploadClient };
|
|
389
|
+
export default PolgoUploadClient;
|
|
390
|
+
|