2022-11-25 16:01:46 +01:00
|
|
|
import newid from "./newid"
|
|
|
|
import { Row, View, Document } from "@budibase/types"
|
2021-09-20 19:24:09 +02:00
|
|
|
|
2022-03-29 17:03:44 +02:00
|
|
|
// bypass the main application db config
|
|
|
|
// use in memory pouchdb directly
|
2022-11-25 16:01:46 +01:00
|
|
|
import { db as dbCore } from "@budibase/backend-core"
|
2022-11-22 20:49:59 +01:00
|
|
|
const Pouch = dbCore.getPouch({ inMemory: true })
|
2021-09-20 19:24:09 +02:00
|
|
|
|
2022-11-25 16:01:46 +01:00
|
|
|
export async function runView(
|
|
|
|
view: View,
|
2022-11-26 16:42:53 +01:00
|
|
|
calculation: string,
|
|
|
|
group: boolean,
|
2022-11-25 16:01:46 +01:00
|
|
|
data: Row[]
|
|
|
|
) {
|
2021-09-21 16:59:50 +02:00
|
|
|
// use a different ID each time for the DB, make sure they
|
|
|
|
// are always unique for each query, don't want overlap
|
|
|
|
// which could cause 409s
|
|
|
|
const db = new Pouch(newid())
|
2022-04-20 18:33:42 +02:00
|
|
|
try {
|
|
|
|
// write all the docs to the in memory Pouch (remove revs)
|
|
|
|
await db.bulkDocs(
|
|
|
|
data.map(row => ({
|
|
|
|
...row,
|
|
|
|
_rev: undefined,
|
|
|
|
}))
|
|
|
|
)
|
2022-11-25 16:01:46 +01:00
|
|
|
let fn = (doc: Document, emit: any) => emit(doc._id)
|
2023-03-02 16:34:52 +01:00
|
|
|
;(0, eval)(
|
|
|
|
"fn = " + view?.map?.replace("function (doc)", "function (doc, emit)")
|
|
|
|
)
|
2022-11-25 16:01:46 +01:00
|
|
|
const queryFns: any = {
|
2022-04-20 18:33:42 +02:00
|
|
|
meta: view.meta,
|
|
|
|
map: fn,
|
|
|
|
}
|
|
|
|
if (view.reduce) {
|
|
|
|
queryFns.reduce = view.reduce
|
2021-09-20 19:24:09 +02:00
|
|
|
}
|
2022-11-25 16:01:46 +01:00
|
|
|
const response: { rows: Row[] } = await db.query(queryFns, {
|
2022-04-20 18:33:42 +02:00
|
|
|
include_docs: !calculation,
|
|
|
|
group: !!group,
|
|
|
|
})
|
|
|
|
// need to fix the revs to be totally accurate
|
|
|
|
for (let row of response.rows) {
|
|
|
|
if (!row._rev || !row._id) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
const found = data.find(possible => possible._id === row._id)
|
|
|
|
if (found) {
|
|
|
|
row._rev = found._rev
|
|
|
|
}
|
2021-09-20 19:24:09 +02:00
|
|
|
}
|
2022-04-20 18:33:42 +02:00
|
|
|
return response
|
|
|
|
} finally {
|
|
|
|
await db.destroy()
|
2022-11-22 20:49:59 +01:00
|
|
|
await dbCore.closePouchDB(db)
|
2021-09-20 19:24:09 +02:00
|
|
|
}
|
|
|
|
}
|