-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
355 lines (283 loc) · 11.3 KB
/
controller.js
File metadata and controls
355 lines (283 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// controller.js
const sql = require('mssql');
const { config, tenantCheck } = require('./constant');
const moment = require('moment');
// api to get the keyValue
const getApi = async (req, res) => {
console.log("getAPIIin ", config)
let pool
try {
pool = new sql.ConnectionPool(config)
await pool.connect()
const transaction = new sql.Transaction(pool)
await transaction.begin()
const request = pool.request();
const keyParam = req.params.key
console.log(keyParam)
let getQuery
if (keyParam) {
getQuery = `select * from [KeyValue] where [key]=@keyParam and ttl IS NULL OR ttl > GETDATE() and is_active=1`
request.input('keyParam', sql.VarChar, keyParam);
}
else {
getQuery = `select * from [KeyValue] where ttl IS NULL OR ttl > GETDATE()and is_active=1 `
}
const result = await request.query(getQuery)
await transaction.commit()
console.log("result", result)
const data = result.recordset
data.forEach(item => {
item.data = JSON.parse(item.data)
// const date = new Date(item.ttl);
// item.ttl = date.toLocaleString();
if (item.ttl) {
item.ttl = moment(item.ttl).format('YYYY-MM-DD HH:mm:ss');
} else {
item.ttl = "NO ttl"
}
})
console.log(data)
if (data === 0) {
res.status(200).send({ status: 200, response: 'No data found' })
} else {
res.status(200).send(data);
}
}
catch (err) {
console.log(err)
await transaction.rollback();
console.error('Error during database transaction: ', err);
res.status(500).send({ status: 500, message: 'Server error' });
}
finally {
if (pool) {
await pool.close();
}
}
}
//api to post the keyValue where the payload should have a key,valu,ttl , and teneantID
const postApi = async (req, res) => {
console.log("postApi ", config)
let pool
try {
pool = new sql.ConnectionPool(config)
await pool.connect()
const transaction = new sql.Transaction(pool)
await transaction.begin()
const request = pool.request();
const { key, data, ttl } = req.body
console.log("payload", key, data, ttl)
const tenant = req.body.tenantID
console.log(tenant);
if (!tenant) {
return res.status(400).send({
error: "Invalid Input",
message: "Tenant ID is required."
});
}
const tenantcheck = await tenantCheck(tenant)
if (!key || !data || !ttl) {
res.status(400).send({
"error": "Missing required field",
"message": "The 'key', 'data', and 'ttl' fields are required."
})
}
const expirationDateTime = moment().add(ttl, 'seconds').toISOString();
console.log(expirationDateTime)
const checkQuery = `SELECT COUNT(*) AS count FROM KeyValue WHERE [key] = @key AND tenantID = @tenantID`;
const checkRequest = new sql.Request(transaction);
checkRequest.input('key', sql.VarChar, key);
checkRequest.input('tenantID', sql.Int, tenant);
const checkResult = await checkRequest.query(checkQuery);
if (checkResult.recordset[0].count > 0) {
// Throw an error for duplicate key
return res.status(409).send({
error: "Duplicate Key Error",
message: `The key '${key}' already exists for tenant ID '${tenant}'.`
});
}
const postQuery = ` INSERT INTO KeyValue ([key], data, ttl,tenantID)
VALUES (@key,@data,@ttl,@tenantID)`;
request.input('key', sql.VarChar, key);
request.input('data', sql.NVarChar, JSON.stringify(data));
request.input('ttl', sql.DateTime, expirationDateTime);
request.input('tenantID', sql.Int, tenant);
console.log(postQuery)
const result = await request.query(postQuery)
const rowsAffected = result.rowsAffected[0];
console.log(rowsAffected);
if (rowsAffected > 0) {
res.status(200).send({ status: 200, response: 'Inserted successfully' })
} else {
res.status(500).send({
"error": "Data Insertion Failed",
"message": "An error occurred while inserting the payload data. Please try again later."
});
}
}
catch (err) {
// Rollback in case of an error
console.log(err);
// Handle unique constraint violation (duplicate key)
if (err.number === 2627 || err.number === 2601) {
return res.status(409).send({
"error": "Duplicate Key Error",
"message": "The key already exists in the database."
});
}
if (transaction) await transaction.rollback();
console.error('Error during database transaction: ', err);
return res.status(500).send({ status: 500, message: 'Server error' });
}
finally {
if (pool) {
await pool.close();
}
}
}
//delete api
const deleteApi = async (req, res) => {
console.log("deleteAPi", config)
let pool
try {
pool = new sql.ConnectionPool(config)
await pool.connect()
const transaction = new sql.Transaction(pool)
await transaction.begin()
const request = pool.request()
const keyParam = req.params.key
console.log(keyParam)
if (!keyParam || keyParam === undefined) {
res.status(400).send({ status: 400, response: 'Please specify correct key in path parms to delete' })
}
const tenant = req.body.tenantID
console.log(tenant);
if (!tenant) {
return res.status(400).send({
error: "Invalid Input",
message: "Tenant ID is required."
});
}
const tenantcheck = await tenantCheck(tenant)
const deleteQuery = `
UPDATE KeyValue
SET is_active = 0
WHERE [key] = @keyParam;`; // Ensure it's correctly defined without extra characters
// Set the input parameter
request.input('keyParam', sql.VarChar, keyParam);
console.log(deleteQuery)
const result = await request.query(deleteQuery)
const rowsAffected = result.rowsAffected[0];
console.log(rowsAffected);
if (rowsAffected > 0) {
res.status(200).send({ status: 200, response: 'Deleted successfully"' })
} else {
res.status(500).send({
"error": "Data Deletion Failed",
"message": "An error occurred while deleting the data. Please try again later."
});
}
}
catch (err) {
console.log(err)
await transaction.rollback();
console.error('Error during database transaction: ', err);
res.status(500).send({ status: 500, message: 'Server error' });
}
finally {
if (pool) {
await pool.close()
}
}
}
//api for batch insertion n have included batchSize as 1000
// A batch limit of 1000 balances efficiency and resource utilization.
// Handling more than 1000 entries in a single request could lead to performance issues
// due to the high number of database transactions and potential memory overhead,
// especially when concurrent requests are made by multiple clients.
// This limit helps maintain optimal throughput and minimizes latency.
const batchApi = async (req, res) => {
console.log("postApi ", config);
let pool;
let rowsAffectedTotal = 0; // To keep track of total rows inserted
try {
pool = new sql.ConnectionPool(config);
await pool.connect();
const transaction = new sql.Transaction(pool);
await transaction.begin();
const payload = req.body.keys;
console.log(req.body)
console.log(payload);
const tenant = req.body.tenantID
console.log(tenant);
if (!tenant) {
return res.status(400).send({
error: "Invalid Input",
message: "Tenant ID is required."
});
}
const tenantcheck = await tenantCheck(tenant)
const batchSize = 1000;
for (let i = 0; i < payload.length; i += batchSize) {
const batch = payload.slice(i, i + batchSize);
for (const item of batch) {
const { key, data, ttl } = item;
if (!key || !data || ttl === undefined) {
return res.status(400).send({
error: "Missing required field",
message: "Each item must include 'key', 'data', and 'ttl'."
});
}
const expirationDateTime = moment().add(ttl, 'seconds').toISOString();
const request = new sql.Request(transaction);
const checkQuery = `SELECT COUNT(*) AS count FROM KeyValue WHERE [key] = @key AND tenantID = @tenantID`;
const checkRequest = new sql.Request(transaction);
checkRequest.input('key', sql.VarChar, key);
checkRequest.input('tenantID', sql.Int, tenant);
const checkResult = await checkRequest.query(checkQuery);
if (checkResult.recordset[0].count > 0) {
// Throw an error for duplicate key
return res.status(409).send({
error: "Duplicate Key Error",
message: `The key '${key}' already exists for tenant ID '${tenant}'.`
});
}
const postQuery = ` INSERT INTO KeyValue ([key], data, ttl,tenantID)
VALUES (@key,@data,@ttl,@tenantID)`;
request.input('key', sql.VarChar, key);
request.input('data', sql.NVarChar, JSON.stringify(data));
request.input('ttl', sql.DateTime, expirationDateTime);
request.input('tenantID', sql.Int, tenant);
const result = await request.query(postQuery);
rowsAffectedTotal += result.rowsAffected[0];
}
}
await transaction.commit();
if (rowsAffectedTotal > 0) {
return res.status(200).send({ status: 200, response: 'Inserted successfully', totalRecordsInserted: rowsAffectedTotal });
} else {
return res.status(500).send({
error: "Data Insertion Failed",
message: "An error occurred while inserting the payload data. Please try again later."
});
}
} catch (err) {
console.log(err);
if (err.number === 2627 || err.number === 2601) {
return res.status(409).send({
"error": "Duplicate Key Error",
"message": "The key already exists in the database."
});
}
if (transaction) await transaction.rollback();
console.error('Error during database transaction: ', err);
return res.status(500).send({ status: 500, message: 'Server error' });
} finally {
if (pool) {
await pool.close();
}
}
};
module.exports = {
getApi, postApi, deleteApi, batchApi
};