/
couchbase.js
65 lines (53 loc) · 1.53 KB
/
couchbase.js
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
import * as couchbase from 'couchbase'
const COUCHBASE_USER = process.env.COUCHBASE_USER
const COUCHBASE_PASSWORD = process.env.COUCHBASE_PASSWORD
const COUCHBASE_ENDPOINT = process.env.COUCHBASE_ENDPOINT || 'localhost'
const COUCHBASE_BUCKET = process.env.COUCHBASE_BUCKET || 'travel-sample'
let IS_CLOUD_INSTANCE = process.env.IS_CLOUD_INSTANCE || 'false'
if (!COUCHBASE_USER) {
throw new Error(
'Please define the COUCHBASE_USER environment variable inside .env.local'
)
}
if (!COUCHBASE_PASSWORD) {
throw new Error(
'Please define the COUCHBASE_PASSWORD environment variable inside .env.local'
)
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.couchbase
if (!cached) {
cached = global.couchbase = { conn: null }
}
async function createCouchbaseCluster() {
if (cached.conn) {
return cached.conn
}
cached.conn = await couchbase.connect(
'couchbase://' +
COUCHBASE_ENDPOINT +
(IS_CLOUD_INSTANCE === 'true'
? '?ssl=no_verify&console_log_level=5'
: ''),
{
username: COUCHBASE_USER,
password: COUCHBASE_PASSWORD,
}
)
return cached.conn
}
export async function connectToDatabase() {
const cluster = await createCouchbaseCluster()
const bucket = cluster.bucket(COUCHBASE_BUCKET)
const collection = bucket.defaultCollection()
let dbConnection = {
cluster,
bucket,
collection,
}
return dbConnection
}