-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk-connection-nodejs.js
More file actions
89 lines (74 loc) · 2.22 KB
/
sdk-connection-nodejs.js
File metadata and controls
89 lines (74 loc) · 2.22 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
/**
* Couchbase SDK connection singleton — Node.js
* Copy and adapt for your application.
*
* Dependencies:
* npm install couchbase
*/
'use strict';
const couchbase = require('couchbase');
// --- Configuration ---
const CB_HOST = 'localhost'; // or 'cb.xxxxx.cloud.couchbase.com' for Capella
const CB_USER = 'app-service-user';
const CB_PASSWORD = 'AppSecret123!';
const CB_BUCKET = 'myapp';
const CB_SCOPE = '_default';
const CB_COLLECTION = '_default';
let cluster = null;
let collection = null;
/**
* Returns the singleton Collection, initializing the cluster on first call.
* @returns {Promise<couchbase.Collection>}
*/
async function getCollection() {
if (collection) return collection;
await init();
return collection;
}
/**
* Returns the singleton Cluster (needed for queries and transactions).
* @returns {Promise<couchbase.Cluster>}
*/
async function getCluster() {
await getCollection(); // ensures cluster is initialized
return cluster;
}
async function init() {
// Use 'couchbases://' for TLS (required for Capella, recommended for production)
cluster = await couchbase.connect(`couchbase://${CB_HOST}`, {
username: CB_USER,
password: CB_PASSWORD,
timeouts: {
connectTimeout: 10_000, // ms
kvTimeout: 2_500,
queryTimeout: 75_000,
searchTimeout: 75_000,
},
});
const bucket = cluster.bucket(CB_BUCKET);
collection = bucket.scope(CB_SCOPE).collection(CB_COLLECTION);
}
/** Call on application shutdown to release resources. */
async function close() {
if (cluster) await cluster.close();
}
module.exports = { getCollection, getCluster, close };
// --- Usage example ---
if (require.main === module) {
(async () => {
const col = await getCollection();
const cl = await getCluster();
// KV upsert
await col.upsert('doc_1', { type: 'example', value: 42 });
// KV get
const result = await col.get('doc_1');
console.log(result.content);
// SQL++ query
const rows = await cl.query(
'SELECT * FROM `myapp`._default._default WHERE type = $type LIMIT 5',
{ parameters: { type: 'example' } }
);
for (const row of rows.rows) console.log(row);
await close();
})();
}