reddb-sdk 1.0.5 → 3.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.
@@ -2,7 +2,7 @@ const fetch = require('node-fetch');
2
2
 
3
3
  class RedDBClient {
4
4
  constructor(baseURL, reddbPassword, adminPassword = null, options = {}) {
5
- if (!baseURL) throw new Error('baseURL é obrigatório');
5
+ if (!baseURL) throw new Error('Base URL is required');
6
6
 
7
7
  this.baseURL = baseURL.replace(/\/$/, '');
8
8
  this.reddbPassword = reddbPassword;
@@ -19,11 +19,10 @@ class RedDBClient {
19
19
 
20
20
  async _safeJson(res) {
21
21
  const text = await res.text();
22
-
23
22
  try {
24
23
  return JSON.parse(text);
25
24
  } catch {
26
- throw new Error(`Resposta inválida do servidor:\n${text}`);
25
+ throw new Error(`Invalid server response:\n${text}`);
27
26
  }
28
27
  }
29
28
 
@@ -37,12 +36,8 @@ class RedDBClient {
37
36
  return res;
38
37
  } catch (err) {
39
38
  clearTimeout(id);
40
-
41
- if (err.name === 'AbortError') {
42
- throw new Error('Timeout: cluster não respondeu a tempo');
43
- }
44
-
45
- throw new Error('Cluster offline ou inacessível');
39
+ if (err.name === 'AbortError') throw new Error('Timeout: cluster did not respond in time');
40
+ throw new Error('Cluster offline or unreachable');
46
41
  }
47
42
  }
48
43
 
@@ -50,17 +45,13 @@ class RedDBClient {
50
45
  let url = `${this.baseURL}${path}`;
51
46
  let body = {};
52
47
 
53
- // aceita body como objeto OU string
54
48
  if (options.body) {
55
- body = typeof options.body === 'string'
56
- ? JSON.parse(options.body)
57
- : options.body;
49
+ body = typeof options.body === 'string' ? JSON.parse(options.body) : options.body;
58
50
  }
59
51
 
60
52
  body.reddbPassword = this.reddbPassword;
61
-
62
53
  if (isAdmin) {
63
- if (!this.adminPassword) throw new Error('Admin password não fornecida');
54
+ if (!this.adminPassword) throw new Error('Admin password not provided');
64
55
  body.adminPassword = this.adminPassword;
65
56
  }
66
57
 
@@ -78,67 +69,109 @@ class RedDBClient {
78
69
  try {
79
70
  this._log('Request:', options.method, url);
80
71
 
81
- const res = await this._fetchWithTimeout(url, {
82
- ...options,
83
- headers
84
- });
85
-
72
+ const res = await this._fetchWithTimeout(url, { ...options, headers });
86
73
  const data = await this._safeJson(res);
87
74
 
88
- // 🔥 tratamento de erro da API
89
- if (!res.ok || data.error) {
90
- throw new Error(data.error || `Erro HTTP ${res.status}`);
91
- }
75
+ if (!res.ok || data.error) throw new Error(data.error || `HTTP error ${res.status}`);
92
76
 
93
77
  return data;
94
78
  } catch (err) {
95
- this._log(`Erro (tentativa ${attempt + 1}):`, err.message);
96
-
97
- if (attempt === this.retries) {
98
- throw new Error(`Falha após ${this.retries + 1} tentativas: ${err.message}`);
99
- }
79
+ this._log(`Error (attempt ${attempt + 1}):`, err.message);
80
+ if (attempt === this.retries) throw new Error(`Failed after ${this.retries + 1} attempts: ${err.message}`);
100
81
  }
101
82
  }
102
83
  }
103
84
 
85
+ // =========================
86
+ // CRUD
87
+ // =========================
104
88
  async set(key, value, document = 'users.json') {
105
- return this._request('/set', {
89
+ return this._request('/set', { method: 'POST', body: { key, value, document } }, true);
90
+ }
91
+
92
+ async delete(key, document = 'users.json') {
93
+ return this._request('/delete', { method: 'POST', body: { key, document } }, true);
94
+ }
95
+
96
+ async get(key, document = 'users.json') {
97
+ return this._request(`/get/${encodeURIComponent(key)}`, { method: 'GET', body: { document } });
98
+ }
99
+
100
+ async listKeys(document = 'users.json') {
101
+ return this._request('/listKeys', { method: 'GET', body: { document } });
102
+ }
103
+
104
+ async exists(key, document = 'users.json') {
105
+ return this._request(`/exists/${encodeURIComponent(key)}`, { method: 'GET', body: { document } });
106
+ }
107
+
108
+ async update(key, value, document = 'users.json') {
109
+ return this._request('/update', { method: 'POST', body: { key, value, document } }, true);
110
+ }
111
+
112
+ // =========================
113
+ // COLLECTIONS
114
+ // =========================
115
+ async addCollection(collectionName, document = 'users.json') {
116
+ return this._request('/addCollection', { method: 'POST', body: { collectionName, document } }, true);
117
+ }
118
+
119
+ async removeCollection(collectionName, document = 'users.json') {
120
+ return this._request('/removeCollection', { method: 'POST', body: { collectionName, document } }, true);
121
+ }
122
+
123
+ async listCollectionKeys(collection, document = 'users.json') {
124
+ return this._request('/listCollectionKeys', { method: 'GET', body: { collection, document } });
125
+ }
126
+
127
+ async updateCollectionItem(document, collection, key, value) {
128
+ return this._request('/updateCollectionItem', {
106
129
  method: 'POST',
107
- body: { key, value, document }
130
+ body: { document, collection, key, value }
108
131
  }, true);
109
132
  }
110
133
 
111
- async delete(key, document = 'users.json') {
112
- return this._request('/delete', {
134
+ async deleteCollectionItem(document, collection, key) {
135
+ return this._request('/deleteCollectionItem', {
113
136
  method: 'POST',
114
- body: { key, document }
137
+ body: { document, collection, key }
115
138
  }, true);
116
139
  }
117
140
 
118
- async get(key, document = 'users.json') {
119
- return this._request(`/get/${encodeURIComponent(key)}`, {
141
+ async getCollectionItem(document, collection, key) {
142
+ return this._request('/getCollectionItem', {
120
143
  method: 'GET',
121
- body: { document }
144
+ body: { document, collection, key }
122
145
  });
123
146
  }
124
147
 
125
- async listKeys(document = 'users.json') {
126
- return this._request('/listKeys', {
148
+ async listCollectionItems(document, collection) {
149
+ return this._request('/listCollectionItems', {
127
150
  method: 'GET',
128
- body: { document }
151
+ body: { document, collection }
129
152
  });
130
153
  }
131
154
 
155
+ // =========================
156
+ // DOCUMENT
157
+ // =========================
158
+ async getDocument(document) {
159
+ return this._request('/getDocument', { method: 'GET', body: { document } });
160
+ }
161
+
162
+ // =========================
163
+ // ADMIN
164
+ // =========================
132
165
  async reset() {
133
- return this._request('/admin/reset', {
134
- method: 'POST'
135
- }, true);
166
+ return this._request('/admin/reset', { method: 'POST' }, true);
136
167
  }
137
168
 
138
169
  async listAdminKeys() {
139
- return this._request('/admin/keys', {
140
- method: 'POST'
141
- }, true);
170
+ return this._request('/admin/keys', { method: 'POST' }, true);
171
+ }
172
+
173
+ async backup() {
174
+ return this._request('/admin/backup', { method: 'POST' }, true);
142
175
  }
143
176
  }
144
177
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reddb-sdk",
3
- "version": "1.0.5",
3
+ "version": "3.0.0",
4
4
  "description": "SDK Node.js para RedDB Cluster",
5
5
  "main": "lib/RedDBClient.js",
6
6
  "keywords": [
@@ -12,7 +12,8 @@
12
12
  "author": "MagicDB",
13
13
  "license": "MIT",
14
14
  "dependencies": {
15
- "node-fetch": "^2.6.7"
15
+ "node-fetch": "^2.6.7",
16
+ "reddb-sdk": "^1.0.5"
16
17
  },
17
18
  "type": "commonjs"
18
19
  }
package/teste.js ADDED
@@ -0,0 +1,40 @@
1
+ // teste.js
2
+ const RedDBClient = require('reddb-sdk'); // npm link ou npm install reddb-sdk
3
+
4
+ const client = new RedDBClient('http://localhost:3000', 'senha_reddb', 'senha_admin', {
5
+ debug: true // mostra logs detalhados
6
+ });
7
+
8
+ (async () => {
9
+ try {
10
+ console.log('--- Teste RedDB SDK ---');
11
+
12
+ // Criar/atualizar uma chave em batata.json
13
+ const setResult = await client.set('batata', 'valor da batata', 'batata.json');
14
+ console.log('SET:', setResult);
15
+
16
+ // Ler a chave
17
+ const getResult = await client.get('batata', 'batata.json');
18
+ console.log('GET:', getResult);
19
+
20
+ // Listar chaves do documento
21
+ const listKeysResult = await client.listKeys('batata.json');
22
+ console.log('LIST KEYS:', listKeysResult);
23
+
24
+ // Deletar a chave
25
+ const deleteResult = await client.delete('batata', 'batata.json');
26
+ console.log('DELETE:', deleteResult);
27
+
28
+ // Criar outro documento sem resetar
29
+ await client.set('minhaChave', 'meuValor', 'meu_doc.json');
30
+ console.log('SET novo documento:', await client.listKeys('meu_doc.json'));
31
+
32
+ // Listar chaves do admin
33
+ const adminKeys = await client.listAdminKeys();
34
+ console.log('ADMIN KEYS:', adminKeys);
35
+
36
+ console.log('--- Teste finalizado ---');
37
+ } catch (err) {
38
+ console.error('Erro no teste RedDB SDK:', err);
39
+ }
40
+ })();