2022-10-12 18:02:23 +02:00
|
|
|
import env from "../environment"
|
2022-11-09 17:53:42 +01:00
|
|
|
import { CouchFindOptions } from "@budibase/types"
|
2022-11-11 13:46:32 +01:00
|
|
|
import { directCouchQuery, PouchLike } from "./couch"
|
|
|
|
export { init, PouchLike, getPouch, getPouchDB } from "./couch"
|
2021-04-20 18:17:44 +02:00
|
|
|
|
2022-03-29 17:03:44 +02:00
|
|
|
let initialised = false
|
2022-05-20 19:29:37 +02:00
|
|
|
const dbList = new Set()
|
2022-03-29 17:03:44 +02:00
|
|
|
|
|
|
|
const checkInitialised = () => {
|
|
|
|
if (!initialised) {
|
|
|
|
throw new Error("init has not been called")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-09 17:53:42 +01:00
|
|
|
export function getDB(dbName: string, opts?: any): PouchLike {
|
2022-05-20 19:29:37 +02:00
|
|
|
if (env.isTest()) {
|
|
|
|
dbList.add(dbName)
|
|
|
|
}
|
2022-11-08 17:32:13 +01:00
|
|
|
return new PouchLike(dbName, opts)
|
|
|
|
}
|
|
|
|
|
2022-04-19 20:42:52 +02: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
|
2022-10-12 18:02:23 +02:00
|
|
|
export async function doWithDB(dbName: string, cb: any, opts = {}) {
|
2022-11-09 17:53:42 +01:00
|
|
|
const db = getDB(dbName, opts)
|
2022-04-19 20:42:52 +02:00
|
|
|
// need this to be async so that we can correctly close DB after all
|
|
|
|
// async operations have been completed
|
2022-11-08 17:32:13 +01:00
|
|
|
return await cb(db)
|
2022-04-19 20:42:52 +02:00
|
|
|
}
|
|
|
|
|
2022-10-12 18:02:23 +02:00
|
|
|
export function allDbs() {
|
2022-05-20 19:29:37 +02:00
|
|
|
if (!env.isTest()) {
|
|
|
|
throw new Error("Cannot be used outside test environment.")
|
|
|
|
}
|
2022-03-29 17:03:44 +02:00
|
|
|
checkInitialised()
|
2022-05-20 19:29:37 +02:00
|
|
|
return [...dbList]
|
2021-05-14 17:31:07 +02:00
|
|
|
}
|
2022-10-12 18:02:23 +02:00
|
|
|
|
2022-10-12 18:57:31 +02:00
|
|
|
export async function directCouchAllDbs(queryString?: string) {
|
|
|
|
let couchPath = "/_all_dbs"
|
|
|
|
if (queryString) {
|
|
|
|
couchPath += `?${queryString}`
|
|
|
|
}
|
|
|
|
return await directCouchQuery(couchPath)
|
|
|
|
}
|
|
|
|
|
2022-10-12 18:02:23 +02:00
|
|
|
export async function directCouchFind(dbName: string, opts: CouchFindOptions) {
|
|
|
|
const json = await directCouchQuery(`${dbName}/_find`, "POST", opts)
|
|
|
|
return { rows: json.docs, bookmark: json.bookmark }
|
|
|
|
}
|