@jpzinhdwbr/request 0.0.0-stage → 1.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.
package/README.md CHANGED
@@ -1,3 +1,261 @@
1
- # Temporary Holding Version
1
+ @jpzinhdwbr/request
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Biblioteca de requisições HTTP da DevWorld BR, desenvolvida para facilitar a comunicação com os serviços e endpoints da plataforma.
4
+
5
+ O pacote utiliza o "fetch" nativo do Node.js e oferece diferentes formatos de resposta, incluindo JSON, Buffer, Stream e texto.
6
+
7
+ Ideal para quem deseja realizar requisições diretamente à API da DevWorld BR, sem precisar utilizar a SDK oficial.
8
+
9
+ 🔗 Links oficiais
10
+
11
+ - Site: https://devworldbr.site
12
+ - API: https://api.devworldbr.site
13
+ - Desenvolvedor: jpzinh #DevWorldBR
14
+
15
+ 📦 Instalação
16
+
17
+ npm install @jpzinhdwbr/request
18
+
19
+ 🚀 Importação
20
+
21
+ O pacote oferece suporte aos ambientes CommonJS e ES Modules.
22
+
23
+ CommonJS
24
+
25
+ const {
26
+ request,
27
+ requestBuffer,
28
+ requestStream,
29
+ requestPath
30
+ } = require('@jpzinhdwbr/request');
31
+
32
+ ES Modules
33
+
34
+ import {
35
+ request,
36
+ requestBuffer,
37
+ requestStream,
38
+ requestPath
39
+ } from '@jpzinhdwbr/request';
40
+
41
+ Também é possível importar o pacote inteiro:
42
+
43
+ import Request from '@jpzinhdwbr/request';
44
+
45
+ const { request, requestBuffer } = Request;
46
+
47
+ ⚙️ Métodos disponíveis
48
+
49
+ Método| Descrição
50
+ "request()"| Realiza requisições com resposta JSON.
51
+ "requestBuffer()"| Realiza requisições e retorna um Buffer.
52
+ "requestStream()"| Retorna o corpo da resposta como Stream.
53
+ "requestPath()"| Realiza requisições com resposta JSON.
54
+
55
+ 🧩 Exemplos de utilização
56
+
57
+ 1. Requisição JSON
58
+
59
+ const { request } = require('@jpzinhdwbr/request');
60
+
61
+ const token_id = 'SUA_API_KEY';
62
+
63
+ async function main() {
64
+ const data = await request(
65
+ 'https://api.devworldbr.site/api/...',
66
+ undefined,
67
+ token_id
68
+ );
69
+
70
+ console.log(data);
71
+ }
72
+
73
+ main();
74
+
75
+ 2. Requisição de imagem ou arquivo
76
+
77
+ O método "requestBuffer()" retorna um Buffer do Node.js.
78
+
79
+ const fs = require('node:fs');
80
+ const { requestBuffer } = require('@jpzinhdwbr/request');
81
+
82
+ const token_id = 'SUA_API_KEY';
83
+
84
+ async function main() {
85
+ const buffer = await requestBuffer(
86
+ 'https://api.devworldbr.site/api/...',
87
+ undefined,
88
+ token_id
89
+ );
90
+
91
+ fs.writeFileSync('./imagem.png', buffer);
92
+
93
+ console.log('Arquivo salvo!');
94
+ }
95
+
96
+ main();
97
+
98
+ 3. Requisição Stream
99
+
100
+ Para trabalhar com respostas em fluxo:
101
+
102
+ const { requestStream } = require('@jpzinhdwbr/request');
103
+
104
+ const token_id = 'SUA_API_KEY';
105
+
106
+ async function main() {
107
+ const stream = await requestStream(
108
+ 'https://api.devworldbr.site/api/...',
109
+ undefined,
110
+ token_id
111
+ );
112
+
113
+ console.log(stream);
114
+ }
115
+
116
+ main();
117
+
118
+ 4. Requisição com POST
119
+
120
+ É possível configurar o método HTTP e enviar um corpo JSON através de "options.body".
121
+
122
+ const { request } = require('@jpzinhdwbr/request');
123
+
124
+ const token_id = 'SUA_API_KEY';
125
+
126
+ async function main() {
127
+ const data = await request(
128
+ 'https://api.devworldbr.site/api/...',
129
+ undefined,
130
+ token_id,
131
+ {
132
+ method: 'POST',
133
+ headers: {
134
+ 'Content-Type': 'application/json'
135
+ },
136
+ body: JSON.stringify({
137
+ exemplo: 'DevWorld BR'
138
+ })
139
+ }
140
+ );
141
+
142
+ console.log(data);
143
+ }
144
+
145
+ main();
146
+
147
+ 5. Requisição GET com parâmetros
148
+
149
+ Os parâmetros GET devem estar na própria URL:
150
+
151
+ const { request } = require('@jpzinhdwbr/request');
152
+
153
+ const token_id = 'SUA_API_KEY';
154
+
155
+ async function main() {
156
+ const url = new URL(
157
+ 'https://api.devworldbr.site/api/downloads/instagram/dl/v1'
158
+ );
159
+
160
+ url.searchParams.set(
161
+ 'link',
162
+ 'https://www.instagram.com/reel/EXEMPLO/'
163
+ );
164
+
165
+ url.searchParams.set('quality', '360');
166
+
167
+ const data = await request(
168
+ url.toString(),
169
+ undefined,
170
+ token_id
171
+ );
172
+
173
+ console.log(data);
174
+ }
175
+
176
+ main();
177
+
178
+ 🛠️ Opções disponíveis
179
+
180
+ O quarto argumento dos métodos permite personalizar a requisição.
181
+
182
+ Opção| Tipo| Padrão| Descrição
183
+ "method"| String| "GET"| Método HTTP.
184
+ "timeout"| Number| "120000"| Tempo limite em milissegundos.
185
+ "headers"| Object| "{}"| Headers adicionais.
186
+ "body"| Any| —| Corpo da requisição.
187
+ "signal"| AbortSignal| Interno| O pacote controla o timeout com AbortController.
188
+
189
+ Exemplo:
190
+
191
+ const data = await request(
192
+ 'https://api.devworldbr.site/api/...',
193
+ undefined,
194
+ token_id,
195
+ {
196
+ method: 'GET',
197
+ timeout: 30000,
198
+ headers: {
199
+ 'Accept': 'application/json'
200
+ }
201
+ }
202
+ );
203
+
204
+ 🔐 Autenticação
205
+
206
+ Quando uma API Key é fornecida, o pacote adiciona automaticamente o seguinte header:
207
+
208
+ dwbr-token-id: SUA_API_KEY
209
+
210
+ A chave é enviada individualmente em cada requisição.
211
+
212
+ ⚠️ Tratamento de erros
213
+
214
+ O pacote trata erros HTTP e de conexão, retornando mensagens identificáveis.
215
+
216
+ try {
217
+ const data = await request(
218
+ 'https://api.devworldbr.site/api/...',
219
+ undefined,
220
+ token_id
221
+ );
222
+
223
+ console.log(data);
224
+ } catch (error) {
225
+ console.error('Erro:', error.message);
226
+
227
+ if (error.status) {
228
+ console.log('Status HTTP:', error.status);
229
+ }
230
+ }
231
+
232
+ Exemplos de mensagens:
233
+
234
+ DevWorld BR Request (401): Unauthorized
235
+ DevWorld BR Request (502): Bad Gateway
236
+ DevWorld BR Request: Tempo limite da requisição excedido.
237
+
238
+ 📋 Informações técnicas
239
+
240
+ - Desenvolvido para Node.js.
241
+ - Utiliza o "fetch" nativo.
242
+ - Suporte a CommonJS.
243
+ - Suporte a ES Modules.
244
+ - Timeout configurável.
245
+ - Autenticação via "dwbr-token-id".
246
+ - Respostas JSON, Buffer, Stream e texto.
247
+ - Tratamento de erros HTTP.
248
+
249
+ 👨‍💻 Desenvolvedor
250
+
251
+ jpzinh #DevWorldBR
252
+
253
+ Desenvolvido para integrar aplicações aos serviços da DevWorld BR.
254
+
255
+ 🌐 https://devworldbr.site
256
+
257
+ 🔗 https://api.devworldbr.site
258
+
259
+ ---
260
+
261
+ © DevWorld BR - Todos os direitos reservados.
@@ -0,0 +1,90 @@
1
+ 'use strict';
2
+
3
+ function toBuffer(data) {
4
+ if (Buffer.isBuffer(data)) return data;
5
+ if (data instanceof ArrayBuffer) {
6
+ return Buffer.from(data);
7
+ }
8
+ if (ArrayBuffer.isView(data)) {
9
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
10
+ }
11
+ throw new TypeError('A resposta não é um Buffer nem um ArrayBuffer válido.');
12
+ }
13
+
14
+ async function Fetch(url, key, options = {}, responseType = 'json') {
15
+ const {
16
+ method = 'GET',
17
+ timeout = 120000,
18
+ headers = {},
19
+ body,
20
+ ...rest
21
+ } = options;
22
+
23
+ const controller = new AbortController();
24
+ const timer = setTimeout(() => controller.abort(), timeout);
25
+
26
+ try {
27
+ const response = await fetch(url, {
28
+ ...rest,
29
+ method: String(method).toUpperCase(),
30
+ headers: {
31
+ Accept: 'application/json, text/plain, */*',
32
+ ...(key ? { 'dwbr-token-id': key } : {}),
33
+ ...headers
34
+ },
35
+ ...(body !== undefined ? { body } : {}),
36
+ signal: controller.signal
37
+ });
38
+
39
+ let data;
40
+
41
+ switch (responseType) {
42
+ case 'arraybuffer':
43
+ data = toBuffer(await response.arrayBuffer())
44
+ break;
45
+
46
+ case 'stream':
47
+ data = response.body;
48
+ break;
49
+
50
+ case 'text':
51
+ data = await response.text();
52
+ break;
53
+
54
+ default:
55
+ data = await response.json();
56
+ break;
57
+ }
58
+
59
+ if (!response.ok) {
60
+ const message =
61
+ data?.msg ||
62
+ data?.message ||
63
+ data?.error ||
64
+ response.statusText;
65
+
66
+ throw Object.assign(new Error(message), {
67
+ status: response.status
68
+ });
69
+ }
70
+
71
+ return data;
72
+ } catch (error) {
73
+ if (error.name === 'AbortError') {
74
+ throw new Error('DevWorld BR Request: Tempo limite da requisição excedido.');
75
+ }
76
+
77
+ if (error.status) {
78
+ throw new Error(
79
+ `DevWorld BR Request (${error.status}): ${error.message}`
80
+ );
81
+ }
82
+
83
+ throw new Error(`DevWorld BR Request: ${error.message}`);
84
+ } finally {
85
+ clearTimeout(timer);
86
+ }
87
+ }
88
+
89
+ module.exports = Fetch;
90
+ module.exports.Fetch = Fetch;
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@jpzinhdwbr/request",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Sistema de requisições HTTP da DevWorld BR",
5
+ "main": "./src/index.js",
6
+ "module": "./src/index.mjs",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "import": "./src/index.mjs",
12
+ "require": "./src/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "src",
17
+ "funcoes"
18
+ ],
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "license": "MIT"
6
23
  }
package/src/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export declare const request: any;
2
+ export declare const requestBuffer: any;
3
+ export declare const requestStream: any;
4
+ export declare const requestPath: any;
5
+ declare const _default: {
6
+ request: any;
7
+ requestBuffer: any;
8
+ requestStream: any;
9
+ requestPath: any;
10
+ };
11
+ export default _default;
package/src/index.js ADDED
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ const Fetch = require('../funcoes/fetch.js');
4
+
5
+ function request(url, params, key, options = {}) {
6
+ return Fetch(url, key, {
7
+ ...options,
8
+ ...(params !== undefined ? { params } : {})
9
+ }, 'json');
10
+ }
11
+
12
+ function requestBuffer(url, params, key, options = {}) {
13
+ return Fetch(url, key, {
14
+ ...options,
15
+ ...(params !== undefined ? { params } : {})
16
+ }, 'arraybuffer');
17
+ }
18
+
19
+ function requestStream(url, params, key, options = {}) {
20
+ return Fetch(url, key, {
21
+ ...options,
22
+ ...(params !== undefined ? { params } : {})
23
+ }, 'stream');
24
+ }
25
+
26
+ function requestPath(url, params, key, options = {}) {
27
+ return Fetch(url, key, {
28
+ ...options,
29
+ ...(params !== undefined ? { params } : {})
30
+ }, 'json');
31
+ }
32
+
33
+ module.exports = {
34
+ request,
35
+ requestBuffer,
36
+ requestStream,
37
+ requestPath
38
+ };
package/src/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import pkg from './index.js';
2
+ export default pkg;
3
+ export const { request, requestBuffer, requestStream, requestPath } = pkg;