reddb-sdk 1.0.4 → 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.
@@ -2,12 +2,14 @@ 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('Base URL is required');
6
+
5
7
  this.baseURL = baseURL.replace(/\/$/, '');
6
8
  this.reddbPassword = reddbPassword;
7
9
  this.adminPassword = adminPassword;
8
10
 
9
11
  this.timeout = options.timeout || 5000;
10
- this.retries = options.retries || 2;
12
+ this.retries = options.retries ?? 2;
11
13
  this.debug = options.debug || false;
12
14
  }
13
15
 
@@ -21,7 +23,7 @@ class RedDBClient {
21
23
  try {
22
24
  return JSON.parse(text);
23
25
  } catch {
24
- throw new Error(`Resposta inválida do servidor:\n${text}`);
26
+ throw new Error(`Invalid server response:\n${text}`);
25
27
  }
26
28
  }
27
29
 
@@ -37,21 +39,28 @@ class RedDBClient {
37
39
  clearTimeout(id);
38
40
 
39
41
  if (err.name === 'AbortError') {
40
- throw new Error('Timeout: cluster não respondeu a tempo');
42
+ throw new Error('Timeout: cluster did not respond in time');
41
43
  }
42
44
 
43
- throw new Error('Cluster offline ou inacessível');
45
+ throw new Error('Cluster offline or unreachable');
44
46
  }
45
47
  }
46
48
 
47
49
  async _request(path, options = {}, isAdmin = false) {
48
50
  let url = `${this.baseURL}${path}`;
49
- let body = options.body ? JSON.parse(options.body) : {};
51
+ let body = {};
52
+
53
+ // accept body as object or string
54
+ if (options.body) {
55
+ body = typeof options.body === 'string'
56
+ ? JSON.parse(options.body)
57
+ : options.body;
58
+ }
50
59
 
51
60
  body.reddbPassword = this.reddbPassword;
52
61
 
53
62
  if (isAdmin) {
54
- if (!this.adminPassword) throw new Error('Admin password não fornecida');
63
+ if (!this.adminPassword) throw new Error('Admin password not provided');
55
64
  body.adminPassword = this.adminPassword;
56
65
  }
57
66
 
@@ -76,60 +85,94 @@ class RedDBClient {
76
85
 
77
86
  const data = await this._safeJson(res);
78
87
 
79
- if (!res.ok) {
80
- throw new Error(data.error || `Erro HTTP ${res.status}`);
88
+ if (!res.ok || data.error) {
89
+ throw new Error(data.error || `HTTP error ${res.status}`);
81
90
  }
82
91
 
83
92
  return data;
84
93
  } catch (err) {
85
- this._log(`Erro (tentativa ${attempt + 1}):`, err.message);
94
+ this._log(`Error (attempt ${attempt + 1}):`, err.message);
86
95
 
87
96
  if (attempt === this.retries) {
88
- throw new Error(`Falha após ${this.retries + 1} tentativas: ${err.message}`);
97
+ throw new Error(`Failed after ${this.retries + 1} attempts: ${err.message}`);
89
98
  }
90
99
  }
91
100
  }
92
101
  }
93
102
 
103
+ // =========================
104
+ // CRUD
105
+ // =========================
94
106
  async set(key, value, document = 'users.json') {
95
107
  return this._request('/set', {
96
108
  method: 'POST',
97
- body: JSON.stringify({ key, value, document })
109
+ body: { key, value, document }
98
110
  }, true);
99
111
  }
100
112
 
101
113
  async delete(key, document = 'users.json') {
102
114
  return this._request('/delete', {
103
115
  method: 'POST',
104
- body: JSON.stringify({ key, document })
116
+ body: { key, document }
105
117
  }, true);
106
118
  }
107
119
 
108
120
  async get(key, document = 'users.json') {
109
121
  return this._request(`/get/${encodeURIComponent(key)}`, {
110
122
  method: 'GET',
111
- body: JSON.stringify({ document })
123
+ body: { document }
112
124
  });
113
125
  }
114
126
 
115
127
  async listKeys(document = 'users.json') {
116
128
  return this._request('/listKeys', {
117
129
  method: 'GET',
118
- body: JSON.stringify({ document })
130
+ body: { document }
119
131
  });
120
132
  }
121
133
 
122
- async reset() {
123
- return this._request('/admin/reset', {
124
- method: 'POST'
134
+ async exists(key, document = 'users.json') {
135
+ return this._request(`/exists/${encodeURIComponent(key)}`, {
136
+ method: 'GET',
137
+ body: { document }
138
+ });
139
+ }
140
+
141
+ async update(key, value, document = 'users.json') {
142
+ return this._request('/update', {
143
+ method: 'POST',
144
+ body: { key, value, document }
125
145
  }, true);
126
146
  }
127
147
 
128
- async listAdminKeys() {
129
- return this._request('/admin/keys', {
130
- method: 'POST'
148
+ async addCollection(collectionName, document = 'users.json') {
149
+ return this._request('/addCollection', {
150
+ method: 'POST',
151
+ body: { collectionName, document }
131
152
  }, true);
132
153
  }
154
+
155
+ async listCollectionKeys(collection, document = 'users.json') {
156
+ return this._request('/listCollectionKeys', {
157
+ method: 'GET',
158
+ body: { collection, document }
159
+ });
160
+ }
161
+
162
+ // =========================
163
+ // Admin
164
+ // =========================
165
+ async reset() {
166
+ return this._request('/admin/reset', { method: 'POST' }, true);
167
+ }
168
+
169
+ async listAdminKeys() {
170
+ return this._request('/admin/keys', { method: 'POST' }, true);
171
+ }
172
+
173
+ async backup() {
174
+ return this._request('/admin/backup', { method: 'POST' }, true);
175
+ }
133
176
  }
134
177
 
135
178
  module.exports = RedDBClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reddb-sdk",
3
- "version": "1.0.4",
3
+ "version": "2.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
+ })();