2023-02-13 12:57:30 +01:00
|
|
|
import { directCouchQuery, DatabaseImpl } from "./couch"
|
2023-11-08 17:17:24 +01:00
|
|
|
import { CouchFindOptions, Database, DatabaseOpts } from "@budibase/types"
|
2024-01-02 12:36:32 +01:00
|
|
|
import { DDInstrumentedDatabase } from "./instrumentation"
|
2022-11-14 19:00:20 +01:00
|
|
|
|
2023-11-08 17:17:24 +01:00
|
|
|
export function getDB(dbName: string, opts?: DatabaseOpts): Database {
|
2024-01-02 12:36:32 +01:00
|
|
|
return new DDInstrumentedDatabase(new DatabaseImpl(dbName, opts))
|
2022-11-14 19:00:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// we have to use a callback for this so that we can close
|
|
|
|
// the DB when we're done, without this manual requests would
|
|
|
|
// need to close the database when done with it to avoid memory leaks
|
2023-09-04 13:23:21 +02:00
|
|
|
export async function doWithDB<T>(
|
|
|
|
dbName: string,
|
|
|
|
cb: (db: Database) => Promise<T>,
|
2023-11-08 17:17:24 +01:00
|
|
|
opts?: DatabaseOpts
|
2023-09-04 13:23:21 +02:00
|
|
|
) {
|
2022-11-14 19:00:20 +01:00
|
|
|
const db = getDB(dbName, opts)
|
|
|
|
// need this to be async so that we can correctly close DB after all
|
|
|
|
// async operations have been completed
|
|
|
|
return await cb(db)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function directCouchAllDbs(queryString?: string) {
|
|
|
|
let couchPath = "/_all_dbs"
|
|
|
|
if (queryString) {
|
|
|
|
couchPath += `?${queryString}`
|
|
|
|
}
|
|
|
|
return await directCouchQuery(couchPath)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function directCouchFind(dbName: string, opts: CouchFindOptions) {
|
|
|
|
const json = await directCouchQuery(`${dbName}/_find`, "POST", opts)
|
|
|
|
return { rows: json.docs, bookmark: json.bookmark }
|
|
|
|
}
|