1
0
Fork 0
mirror of synced 2024-10-02 01:56:57 +13:00

Type internal db.get

This commit is contained in:
Adria Navarro 2023-07-18 11:41:51 +02:00
parent 1072292b9f
commit 2698e47ec4
40 changed files with 144 additions and 120 deletions

@ -1 +1 @@
Subproject commit 544c7e067de69832469cde673e59501480d6d98a Subproject commit 1929d93660e95f4b190d1936d0b3c65c4ad6a1f5

View file

@ -1,5 +1,5 @@
import { events } from "@budibase/backend-core" import { events } from "@budibase/backend-core"
import { AnalyticsPingRequest, PingSource } from "@budibase/types" import { AnalyticsPingRequest, App, PingSource } from "@budibase/types"
import { DocumentType, isDevAppID } from "../../db/utils" import { DocumentType, isDevAppID } from "../../db/utils"
import { context } from "@budibase/backend-core" import { context } from "@budibase/backend-core"
@ -16,7 +16,7 @@ export const ping = async (ctx: any) => {
switch (body.source) { switch (body.source) {
case PingSource.APP: { case PingSource.APP: {
const db = context.getAppDB({ skip_setup: true }) const db = context.getAppDB({ skip_setup: true })
const appInfo = await db.get(DocumentType.APP_METADATA) const appInfo = await db.get<App>(DocumentType.APP_METADATA)
let appId = context.getAppId() let appId = context.getAppId()
if (isDevAppID(appId)) { if (isDevAppID(appId)) {

View file

@ -6,7 +6,7 @@ const KEYS_DOC = dbCore.StaticDatabases.GLOBAL.docs.apiKeys
async function getBuilderMainDoc() { async function getBuilderMainDoc() {
const db = tenancy.getGlobalDB() const db = tenancy.getGlobalDB()
try { try {
return await db.get(KEYS_DOC) return await db.get<any>(KEYS_DOC)
} catch (err) { } catch (err) {
// doesn't exist yet, nothing to get // doesn't exist yet, nothing to get
return { return {

View file

@ -222,7 +222,7 @@ export async function fetchAppDefinition(ctx: UserCtx) {
export async function fetchAppPackage(ctx: UserCtx) { export async function fetchAppPackage(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
let application = await db.get(DocumentType.APP_METADATA) let application = await db.get<any>(DocumentType.APP_METADATA)
const layouts = await getLayouts() const layouts = await getLayouts()
let screens = await getScreens() let screens = await getScreens()
const license = await licensing.cache.getCachedLicense() const license = await licensing.cache.getCachedLicense()
@ -458,7 +458,7 @@ export async function update(ctx: UserCtx) {
export async function updateClient(ctx: UserCtx) { export async function updateClient(ctx: UserCtx) {
// Get current app version // Get current app version
const db = context.getAppDB() const db = context.getAppDB()
const application = await db.get(DocumentType.APP_METADATA) const application = await db.get<App>(DocumentType.APP_METADATA)
const currentVersion = application.version const currentVersion = application.version
// Update client library and manifest // Update client library and manifest
@ -482,7 +482,7 @@ export async function updateClient(ctx: UserCtx) {
export async function revertClient(ctx: UserCtx) { export async function revertClient(ctx: UserCtx) {
// Check app can be reverted // Check app can be reverted
const db = context.getAppDB() const db = context.getAppDB()
const application = await db.get(DocumentType.APP_METADATA) const application = await db.get<App>(DocumentType.APP_METADATA)
if (!application.revertableVersion) { if (!application.revertableVersion) {
ctx.throw(400, "There is no version to revert to") ctx.throw(400, "There is no version to revert to")
} }
@ -535,7 +535,7 @@ async function destroyApp(ctx: UserCtx) {
const db = dbCore.getDB(devAppId) const db = dbCore.getDB(devAppId)
// standard app deletion flow // standard app deletion flow
const app = await db.get(DocumentType.APP_METADATA) const app = await db.get<App>(DocumentType.APP_METADATA)
const result = await db.destroy() const result = await db.destroy()
await quotas.removeApp() await quotas.removeApp()
await events.app.deleted(app) await events.app.deleted(app)
@ -598,7 +598,7 @@ export async function sync(ctx: UserCtx) {
export async function updateAppPackage(appPackage: any, appId: any) { export async function updateAppPackage(appPackage: any, appId: any) {
return context.doInAppContext(appId, async () => { return context.doInAppContext(appId, async () => {
const db = context.getAppDB() const db = context.getAppDB()
const application = await db.get(DocumentType.APP_METADATA) const application = await db.get<App>(DocumentType.APP_METADATA)
const newAppPackage = { ...application, ...appPackage } const newAppPackage = { ...application, ...appPackage }
if (appPackage._rev !== application._rev) { if (appPackage._rev !== application._rev) {

View file

@ -4,6 +4,7 @@ import { getFullUser } from "../../utilities/users"
import { roles, context } from "@budibase/backend-core" import { roles, context } from "@budibase/backend-core"
import { groups } from "@budibase/pro" import { groups } from "@budibase/pro"
import { ContextUser, User, Row, UserCtx } from "@budibase/types" import { ContextUser, User, Row, UserCtx } from "@budibase/types"
import sdk from "../../sdk"
const PUBLIC_ROLE = roles.BUILTIN_ROLE_IDS.PUBLIC const PUBLIC_ROLE = roles.BUILTIN_ROLE_IDS.PUBLIC
@ -41,7 +42,7 @@ export async function fetchSelf(ctx: UserCtx) {
// remove the full roles structure // remove the full roles structure
delete user.roles delete user.roles
try { try {
const userTable = await db.get(InternalTables.USER_METADATA) const userTable = await sdk.tables.getTable(InternalTables.USER_METADATA)
// specifically needs to make sure is enriched // specifically needs to make sure is enriched
ctx.body = await outputProcessing(userTable, user as Row) ctx.body = await outputProcessing(userTable, user as Row)
} catch (err: any) { } catch (err: any) {

View file

@ -16,6 +16,7 @@ import { setTestFlag, clearTestFlag } from "../../utilities/redis"
import { context, cache, events } from "@budibase/backend-core" import { context, cache, events } from "@budibase/backend-core"
import { automations, features } from "@budibase/pro" import { automations, features } from "@budibase/pro"
import { import {
App,
Automation, Automation,
AutomationActionStepId, AutomationActionStepId,
AutomationResults, AutomationResults,
@ -152,7 +153,7 @@ export async function update(ctx: BBContext) {
return return
} }
const oldAutomation = await db.get(automation._id) const oldAutomation = await db.get<Automation>(automation._id)
automation = cleanAutomationInputs(automation) automation = cleanAutomationInputs(automation)
automation = await checkForWebhooks({ automation = await checkForWebhooks({
oldAuto: oldAutomation, oldAuto: oldAutomation,
@ -210,7 +211,7 @@ export async function find(ctx: BBContext) {
export async function destroy(ctx: BBContext) { export async function destroy(ctx: BBContext) {
const db = context.getAppDB() const db = context.getAppDB()
const automationId = ctx.params.id const automationId = ctx.params.id
const oldAutomation = await db.get(automationId) const oldAutomation = await db.get<Automation>(automationId)
await checkForWebhooks({ await checkForWebhooks({
oldAuto: oldAutomation, oldAuto: oldAutomation,
}) })
@ -229,7 +230,7 @@ export async function clearLogError(ctx: BBContext) {
const { automationId, appId } = ctx.request.body const { automationId, appId } = ctx.request.body
await context.doInAppContext(appId, async () => { await context.doInAppContext(appId, async () => {
const db = context.getProdAppDB() const db = context.getProdAppDB()
const metadata = await db.get(DocumentType.APP_METADATA) const metadata = await db.get<App>(DocumentType.APP_METADATA)
if (!automationId) { if (!automationId) {
delete metadata.automationErrors delete metadata.automationErrors
} else if ( } else if (
@ -267,7 +268,7 @@ export async function getDefinitionList(ctx: BBContext) {
export async function trigger(ctx: BBContext) { export async function trigger(ctx: BBContext) {
const db = context.getAppDB() const db = context.getAppDB()
let automation = await db.get(ctx.params.id) let automation = await db.get<Automation>(ctx.params.id)
let hasCollectStep = sdk.automations.utils.checkForCollectStep(automation) let hasCollectStep = sdk.automations.utils.checkForCollectStep(automation)
if (hasCollectStep && (await features.isSyncAutomationsEnabled())) { if (hasCollectStep && (await features.isSyncAutomationsEnabled())) {
@ -312,8 +313,8 @@ function prepareTestInput(input: any) {
export async function test(ctx: BBContext) { export async function test(ctx: BBContext) {
const db = context.getAppDB() const db = context.getAppDB()
let automation = await db.get(ctx.params.id) let automation = await db.get<Automation>(ctx.params.id)
await setTestFlag(automation._id) await setTestFlag(automation._id!)
const testInput = prepareTestInput(ctx.request.body) const testInput = prepareTestInput(ctx.request.body)
const response = await triggers.externalTrigger( const response = await triggers.externalTrigger(
automation, automation,
@ -328,7 +329,7 @@ export async function test(ctx: BBContext) {
...ctx.request.body, ...ctx.request.body,
occurredAt: new Date().getTime(), occurredAt: new Date().getTime(),
}) })
await clearTestFlag(automation._id) await clearTestFlag(automation._id!)
ctx.body = response ctx.body = response
await events.automation.tested(automation) await events.automation.tested(automation)
} }

View file

@ -1,7 +1,7 @@
import sdk from "../../sdk" import sdk from "../../sdk"
import { events, context, db } from "@budibase/backend-core" import { events, context, db } from "@budibase/backend-core"
import { DocumentType } from "../../db/utils" import { DocumentType } from "../../db/utils"
import { Ctx } from "@budibase/types" import { App, Ctx } from "@budibase/types"
interface ExportAppDumpRequest { interface ExportAppDumpRequest {
excludeRows: boolean excludeRows: boolean
@ -29,7 +29,7 @@ export async function exportAppDump(ctx: Ctx<ExportAppDumpRequest>) {
await context.doInAppContext(appId, async () => { await context.doInAppContext(appId, async () => {
const appDb = context.getAppDB() const appDb = context.getAppDB()
const app = await appDb.get(DocumentType.APP_METADATA) const app = await appDb.get<App>(DocumentType.APP_METADATA)
await events.app.exported(app) await events.app.exported(app)
}) })
} }

View file

@ -1,5 +1,5 @@
import { DocumentType } from "../../db/utils" import { DocumentType } from "../../db/utils"
import { Plugin } from "@budibase/types" import { App, Plugin } from "@budibase/types"
import { db as dbCore, context, tenancy } from "@budibase/backend-core" import { db as dbCore, context, tenancy } from "@budibase/backend-core"
import { getComponentLibraryManifest } from "../../utilities/fileSystem" import { getComponentLibraryManifest } from "../../utilities/fileSystem"
import { UserCtx } from "@budibase/types" import { UserCtx } from "@budibase/types"
@ -7,7 +7,7 @@ import { UserCtx } from "@budibase/types"
export async function fetchAppComponentDefinitions(ctx: UserCtx) { export async function fetchAppComponentDefinitions(ctx: UserCtx) {
try { try {
const db = context.getAppDB() const db = context.getAppDB()
const app = await db.get(DocumentType.APP_METADATA) const app = await db.get<App>(DocumentType.APP_METADATA)
let componentManifests = await Promise.all( let componentManifests = await Promise.all(
app.componentLibraries.map(async (library: any) => { app.componentLibraries.map(async (library: any) => {

View file

@ -433,7 +433,7 @@ export async function destroy(ctx: UserCtx) {
export async function find(ctx: UserCtx) { export async function find(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
const datasource = await db.get(ctx.params.datasourceId) const datasource = await sdk.datasources.get(ctx.params.datasourceId)
ctx.body = await sdk.datasources.removeSecretSingle(datasource) ctx.body = await sdk.datasources.removeSecretSingle(datasource)
} }
@ -449,7 +449,7 @@ export async function query(ctx: UserCtx) {
export async function getExternalSchema(ctx: UserCtx) { export async function getExternalSchema(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
const datasource = await db.get(ctx.params.datasourceId) const datasource = await sdk.datasources.get(ctx.params.datasourceId)
const enrichedDatasource = await getAndMergeDatasource(datasource) const enrichedDatasource = await getAndMergeDatasource(datasource)
const connector = await getConnector(enrichedDatasource) const connector = await getConnector(enrichedDatasource)

View file

@ -7,7 +7,7 @@ import {
enableCronTrigger, enableCronTrigger,
} from "../../../automations/utils" } from "../../../automations/utils"
import { backups } from "@budibase/pro" import { backups } from "@budibase/pro"
import { AppBackupTrigger } from "@budibase/types" import { App, AppBackupTrigger } from "@budibase/types"
import sdk from "../../../sdk" import sdk from "../../../sdk"
import { builderSocket } from "../../../websockets" import { builderSocket } from "../../../websockets"
@ -44,7 +44,7 @@ async function storeDeploymentHistory(deployment: any) {
let deploymentDoc let deploymentDoc
try { try {
// theres only one deployment doc per app database // theres only one deployment doc per app database
deploymentDoc = await db.get(DocumentType.DEPLOYMENTS) deploymentDoc = await db.get<any>(DocumentType.DEPLOYMENTS)
} catch (err) { } catch (err) {
deploymentDoc = { _id: DocumentType.DEPLOYMENTS, history: {} } deploymentDoc = { _id: DocumentType.DEPLOYMENTS, history: {} }
} }
@ -113,7 +113,7 @@ export async function fetchDeployments(ctx: any) {
export async function deploymentProgress(ctx: any) { export async function deploymentProgress(ctx: any) {
try { try {
const db = context.getAppDB() const db = context.getAppDB()
const deploymentDoc = await db.get(DocumentType.DEPLOYMENTS) const deploymentDoc = await db.get<any>(DocumentType.DEPLOYMENTS)
ctx.body = deploymentDoc[ctx.params.deploymentId] ctx.body = deploymentDoc[ctx.params.deploymentId]
} catch (err) { } catch (err) {
ctx.throw( ctx.throw(
@ -165,9 +165,9 @@ export const publishApp = async function (ctx: any) {
// app metadata is excluded as it is likely to be in conflict // app metadata is excluded as it is likely to be in conflict
// replicate the app metadata document manually // replicate the app metadata document manually
const db = context.getProdAppDB() const db = context.getProdAppDB()
const appDoc = await devDb.get(DocumentType.APP_METADATA) const appDoc = await devDb.get<App>(DocumentType.APP_METADATA)
try { try {
const prodAppDoc = await db.get(DocumentType.APP_METADATA) const prodAppDoc = await db.get<App>(DocumentType.APP_METADATA)
appDoc._rev = prodAppDoc._rev appDoc._rev = prodAppDoc._rev
} catch (err) { } catch (err) {
delete appDoc._rev delete appDoc._rev

View file

@ -6,6 +6,7 @@ import { clearLock as redisClearLock } from "../../utilities/redis"
import { DocumentType } from "../../db/utils" import { DocumentType } from "../../db/utils"
import { context, env as envCore } from "@budibase/backend-core" import { context, env as envCore } from "@budibase/backend-core"
import { events, db as dbCore, cache } from "@budibase/backend-core" import { events, db as dbCore, cache } from "@budibase/backend-core"
import { App } from "@budibase/types"
async function redirect(ctx: any, method: string, path: string = "global") { async function redirect(ctx: any, method: string, path: string = "global") {
const { devPath } = ctx.params const { devPath } = ctx.params
@ -81,7 +82,7 @@ export async function revert(ctx: any) {
if (!exists) { if (!exists) {
throw new Error("App must be deployed to be reverted.") throw new Error("App must be deployed to be reverted.")
} }
const deploymentDoc = await db.get(DocumentType.DEPLOYMENTS) const deploymentDoc = await db.get<any>(DocumentType.DEPLOYMENTS)
if ( if (
!deploymentDoc.history || !deploymentDoc.history ||
Object.keys(deploymentDoc.history).length === 0 Object.keys(deploymentDoc.history).length === 0
@ -104,7 +105,7 @@ export async function revert(ctx: any) {
// update appID in reverted app to be dev version again // update appID in reverted app to be dev version again
const db = context.getAppDB() const db = context.getAppDB()
const appDoc = await db.get(DocumentType.APP_METADATA) const appDoc = await db.get<App>(DocumentType.APP_METADATA)
appDoc.appId = appId appDoc.appId = appId
appDoc.instance._id = appId appDoc.instance._id = appId
await db.put(appDoc) await db.put(appDoc)

View file

@ -14,7 +14,7 @@ export async function addRev(
id = DocumentType.APP_METADATA id = DocumentType.APP_METADATA
} }
const db = context.getAppDB() const db = context.getAppDB()
const dbDoc = await db.get(id) const dbDoc = await db.get<any>(id)
body._rev = dbDoc._rev body._rev = dbDoc._rev
// update ID in case it is an app ID // update ID in case it is an app ID
body._id = id body._id = id

View file

@ -9,6 +9,7 @@ import { quotas } from "@budibase/pro"
import { events, context, utils, constants } from "@budibase/backend-core" import { events, context, utils, constants } from "@budibase/backend-core"
import sdk from "../../../sdk" import sdk from "../../../sdk"
import { QueryEvent } from "../../../threads/definitions" import { QueryEvent } from "../../../threads/definitions"
import { Query } from "@budibase/types"
const Runner = new Thread(ThreadType.QUERY, { const Runner = new Thread(ThreadType.QUERY, {
timeoutMs: env.QUERY_THREAD_TIMEOUT || 10000, timeoutMs: env.QUERY_THREAD_TIMEOUT || 10000,
@ -206,7 +207,7 @@ async function execute(
) { ) {
const db = context.getAppDB() const db = context.getAppDB()
const query = await db.get(ctx.params.queryId) const query = await db.get<Query>(ctx.params.queryId)
const { datasource, envVars } = await sdk.datasources.getWithEnvVars( const { datasource, envVars } = await sdk.datasources.getWithEnvVars(
query.datasourceId query.datasourceId
) )
@ -275,7 +276,7 @@ export async function executeV2(
const removeDynamicVariables = async (queryId: any) => { const removeDynamicVariables = async (queryId: any) => {
const db = context.getAppDB() const db = context.getAppDB()
const query = await db.get(queryId) const query = await db.get<Query>(queryId)
const datasource = await sdk.datasources.get(query.datasourceId) const datasource = await sdk.datasources.get(query.datasourceId)
const dynamicVariables = datasource.config?.dynamicVariables as any[] const dynamicVariables = datasource.config?.dynamicVariables as any[]
@ -298,7 +299,7 @@ export async function destroy(ctx: any) {
const db = context.getAppDB() const db = context.getAppDB()
const queryId = ctx.params.queryId const queryId = ctx.params.queryId
await removeDynamicVariables(queryId) await removeDynamicVariables(queryId)
const query = await db.get(queryId) const query = await db.get<Query>(queryId)
const datasource = await sdk.datasources.get(query.datasourceId) const datasource = await sdk.datasources.get(query.datasourceId)
await db.remove(ctx.params.queryId, ctx.params.revId) await db.remove(ctx.params.queryId, ctx.params.revId)
ctx.message = `Query deleted.` ctx.message = `Query deleted.`

View file

@ -1,6 +1,7 @@
import { roles, context, events, db as dbCore } from "@budibase/backend-core" import { roles, context, events, db as dbCore } from "@budibase/backend-core"
import { getUserMetadataParams, InternalTables } from "../../db/utils" import { getUserMetadataParams, InternalTables } from "../../db/utils"
import { UserCtx, Database } from "@budibase/types" import { UserCtx, Database, UserRoles, Role } from "@budibase/types"
import sdk from "../../sdk"
const UpdateRolesOptions = { const UpdateRolesOptions = {
CREATED: "created", CREATED: "created",
@ -13,23 +14,23 @@ async function updateRolesOnUserTable(
updateOption: string, updateOption: string,
roleVersion: string | undefined roleVersion: string | undefined
) { ) {
const table = await db.get(InternalTables.USER_METADATA) const table = await sdk.tables.getTable(InternalTables.USER_METADATA)
const schema = table.schema const schema = table.schema
const remove = updateOption === UpdateRolesOptions.REMOVED const remove = updateOption === UpdateRolesOptions.REMOVED
let updated = false let updated = false
for (let prop of Object.keys(schema)) { for (let prop of Object.keys(schema)) {
if (prop === "roleId") { if (prop === "roleId") {
updated = true updated = true
const constraints = schema[prop].constraints const constraints = schema[prop].constraints!
const updatedRoleId = const updatedRoleId =
roleVersion === roles.RoleIDVersion.NAME roleVersion === roles.RoleIDVersion.NAME
? roles.getExternalRoleID(roleId, roleVersion) ? roles.getExternalRoleID(roleId, roleVersion)
: roleId : roleId
const indexOfRoleId = constraints.inclusion.indexOf(updatedRoleId) const indexOfRoleId = constraints.inclusion!.indexOf(updatedRoleId)
if (remove && indexOfRoleId !== -1) { if (remove && indexOfRoleId !== -1) {
constraints.inclusion.splice(indexOfRoleId, 1) constraints.inclusion!.splice(indexOfRoleId, 1)
} else if (!remove && indexOfRoleId === -1) { } else if (!remove && indexOfRoleId === -1) {
constraints.inclusion.push(updatedRoleId) constraints.inclusion!.push(updatedRoleId)
} }
break break
} }
@ -69,7 +70,7 @@ export async function save(ctx: UserCtx) {
let dbRole let dbRole
if (!isCreate) { if (!isCreate) {
dbRole = await db.get(_id) dbRole = await db.get<UserRoles>(_id)
} }
if (dbRole && dbRole.name !== name && isNewVersion) { if (dbRole && dbRole.name !== name && isNewVersion) {
ctx.throw(400, "Cannot change custom role name") ctx.throw(400, "Cannot change custom role name")
@ -105,7 +106,7 @@ export async function destroy(ctx: UserCtx) {
// make sure has the prefix (if it has it then it won't be added) // make sure has the prefix (if it has it then it won't be added)
roleId = dbCore.generateRoleID(roleId) roleId = dbCore.generateRoleID(roleId)
} }
const role = await db.get(roleId) const role = await db.get<Role>(roleId)
// first check no users actively attached to role // first check no users actively attached to role
const users = ( const users = (
await db.allDocs( await db.allDocs(

View file

@ -16,6 +16,7 @@ import { cloneDeep } from "lodash/fp"
import { context, db as dbCore } from "@budibase/backend-core" import { context, db as dbCore } from "@budibase/backend-core"
import { finaliseRow, updateRelatedFormula } from "./staticFormula" import { finaliseRow, updateRelatedFormula } from "./staticFormula"
import { UserCtx, LinkDocumentValue, Row, Table } from "@budibase/types" import { UserCtx, LinkDocumentValue, Row, Table } from "@budibase/types"
import sdk from "../../../sdk"
export async function patch(ctx: UserCtx) { export async function patch(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
@ -24,7 +25,7 @@ export async function patch(ctx: UserCtx) {
const isUserTable = tableId === InternalTables.USER_METADATA const isUserTable = tableId === InternalTables.USER_METADATA
let oldRow let oldRow
try { try {
let dbTable = await db.get(tableId) let dbTable = await sdk.tables.getTable(tableId)
oldRow = await outputProcessing( oldRow = await outputProcessing(
dbTable, dbTable,
await utils.findRow(ctx, tableId, inputs._id) await utils.findRow(ctx, tableId, inputs._id)
@ -40,7 +41,7 @@ export async function patch(ctx: UserCtx) {
throw "Row does not exist" throw "Row does not exist"
} }
} }
let dbTable = await db.get(tableId) let dbTable = await sdk.tables.getTable(tableId)
// need to build up full patch fields before coerce // need to build up full patch fields before coerce
let combinedRow: any = cloneDeep(oldRow) let combinedRow: any = cloneDeep(oldRow)
for (let key of Object.keys(inputs)) { for (let key of Object.keys(inputs)) {
@ -95,7 +96,7 @@ export async function save(ctx: UserCtx) {
} }
// this returns the table and row incase they have been updated // this returns the table and row incase they have been updated
const dbTable = await db.get(inputs.tableId) const dbTable = await sdk.tables.getTable(inputs.tableId)
// need to copy the table so it can be differenced on way out // need to copy the table so it can be differenced on way out
const tableClone = cloneDeep(dbTable) const tableClone = cloneDeep(dbTable)
@ -127,7 +128,7 @@ export async function save(ctx: UserCtx) {
export async function find(ctx: UserCtx) { export async function find(ctx: UserCtx) {
const db = dbCore.getDB(ctx.appId) const db = dbCore.getDB(ctx.appId)
const table = await db.get(ctx.params.tableId) const table = await sdk.tables.getTable(ctx.params.tableId)
let row = await utils.findRow(ctx, ctx.params.tableId, ctx.params.rowId) let row = await utils.findRow(ctx, ctx.params.tableId, ctx.params.rowId)
row = await outputProcessing(table, row) row = await outputProcessing(table, row)
return row return row
@ -136,13 +137,13 @@ export async function find(ctx: UserCtx) {
export async function destroy(ctx: UserCtx) { export async function destroy(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
const { _id } = ctx.request.body const { _id } = ctx.request.body
let row = await db.get(_id) let row = await db.get<Row>(_id)
let _rev = ctx.request.body._rev || row._rev let _rev = ctx.request.body._rev || row._rev
if (row.tableId !== ctx.params.tableId) { if (row.tableId !== ctx.params.tableId) {
throw "Supplied tableId doesn't match the row's tableId" throw "Supplied tableId doesn't match the row's tableId"
} }
const table = await db.get(row.tableId) const table = await sdk.tables.getTable(row.tableId)
// update the row to include full relationships before deleting them // update the row to include full relationships before deleting them
row = await outputProcessing(table, row, { squash: false }) row = await outputProcessing(table, row, { squash: false })
// now remove the relationships // now remove the relationships
@ -172,7 +173,7 @@ export async function destroy(ctx: UserCtx) {
export async function bulkDestroy(ctx: UserCtx) { export async function bulkDestroy(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
const tableId = ctx.params.tableId const tableId = ctx.params.tableId
const table = await db.get(tableId) const table = await sdk.tables.getTable(tableId)
let { rows } = ctx.request.body let { rows } = ctx.request.body
// before carrying out any updates, make sure the rows are ready to be returned // before carrying out any updates, make sure the rows are ready to be returned
@ -214,7 +215,7 @@ export async function fetchEnrichedRow(ctx: UserCtx) {
const rowId = ctx.params.rowId const rowId = ctx.params.rowId
// need table to work out where links go in row // need table to work out where links go in row
let [table, row] = await Promise.all([ let [table, row] = await Promise.all([
db.get(tableId), sdk.tables.getTable(tableId),
utils.findRow(ctx, tableId, rowId), utils.findRow(ctx, tableId, rowId),
]) ])
// get the link docs // get the link docs

View file

@ -8,8 +8,9 @@ import { FieldTypes, FormulaTypes } from "../../../constants"
import { context } from "@budibase/backend-core" import { context } from "@budibase/backend-core"
import { Table, Row } from "@budibase/types" import { Table, Row } from "@budibase/types"
import * as linkRows from "../../../db/linkedRows" import * as linkRows from "../../../db/linkedRows"
const { isEqual } = require("lodash") import sdk from "../../../sdk"
const { cloneDeep } = require("lodash/fp") import { isEqual } from "lodash"
import { cloneDeep } from "lodash/fp"
/** /**
* This function runs through a list of enriched rows, looks at the rows which * This function runs through a list of enriched rows, looks at the rows which
@ -148,7 +149,7 @@ export async function finaliseRow(
await db.put(table) await db.put(table)
} catch (err: any) { } catch (err: any) {
if (err.status === 409) { if (err.status === 409) {
const updatedTable = await db.get(table._id) const updatedTable = await sdk.tables.getTable(table._id)
let response = processAutoColumn(null, updatedTable, row, { let response = processAutoColumn(null, updatedTable, row, {
reprocessing: true, reprocessing: true,
}) })

View file

@ -7,7 +7,7 @@ import {
roles, roles,
} from "@budibase/backend-core" } from "@budibase/backend-core"
import { updateAppPackage } from "./application" import { updateAppPackage } from "./application"
import { Plugin, ScreenProps, BBContext } from "@budibase/types" import { Plugin, ScreenProps, BBContext, Screen } from "@budibase/types"
import { builderSocket } from "../../websockets" import { builderSocket } from "../../websockets"
export async function fetch(ctx: BBContext) { export async function fetch(ctx: BBContext) {
@ -64,7 +64,7 @@ export async function save(ctx: BBContext) {
}) })
// Update the app metadata // Update the app metadata
const application = await db.get(DocumentType.APP_METADATA) const application = await db.get<any>(DocumentType.APP_METADATA)
let usedPlugins = application.usedPlugins || [] let usedPlugins = application.usedPlugins || []
requiredPlugins.forEach((plugin: Plugin) => { requiredPlugins.forEach((plugin: Plugin) => {
@ -104,7 +104,7 @@ export async function save(ctx: BBContext) {
export async function destroy(ctx: BBContext) { export async function destroy(ctx: BBContext) {
const db = context.getAppDB() const db = context.getAppDB()
const id = ctx.params.screenId const id = ctx.params.screenId
const screen = await db.get(id) const screen = await db.get<Screen>(id)
await db.remove(id, ctx.params.screenRev) await db.remove(id, ctx.params.screenRev)

View file

@ -1,7 +1,7 @@
require("svelte/register") require("svelte/register")
import { join } from "../../../utilities/centralPath" import { join } from "../../../utilities/centralPath"
const uuid = require("uuid") import uuid from "uuid"
import { ObjectStoreBuckets } from "../../../constants" import { ObjectStoreBuckets } from "../../../constants"
import { processString } from "@budibase/string-templates" import { processString } from "@budibase/string-templates"
import { import {
@ -16,6 +16,7 @@ import AWS from "aws-sdk"
import fs from "fs" import fs from "fs"
import sdk from "../../../sdk" import sdk from "../../../sdk"
import * as pro from "@budibase/pro" import * as pro from "@budibase/pro"
import { App } from "@budibase/types"
const send = require("koa-send") const send = require("koa-send")
@ -110,7 +111,7 @@ export const serveApp = async function (ctx: any) {
let db let db
try { try {
db = context.getAppDB({ skip_setup: true }) db = context.getAppDB({ skip_setup: true })
const appInfo = await db.get(DocumentType.APP_METADATA) const appInfo = await db.get<any>(DocumentType.APP_METADATA)
let appId = context.getAppId() let appId = context.getAppId()
if (!env.isJest()) { if (!env.isJest()) {
@ -177,7 +178,7 @@ export const serveApp = async function (ctx: any) {
export const serveBuilderPreview = async function (ctx: any) { export const serveBuilderPreview = async function (ctx: any) {
const db = context.getAppDB({ skip_setup: true }) const db = context.getAppDB({ skip_setup: true })
const appInfo = await db.get(DocumentType.APP_METADATA) const appInfo = await db.get<App>(DocumentType.APP_METADATA)
if (!env.isJest()) { if (!env.isJest()) {
let appId = context.getAppId() let appId = context.getAppId()

View file

@ -323,7 +323,7 @@ export async function save(ctx: UserCtx) {
// Since tables are stored inside datasources, we need to notify clients // Since tables are stored inside datasources, we need to notify clients
// that the datasource definition changed // that the datasource definition changed
const updatedDatasource = await db.get(datasource._id) const updatedDatasource = await sdk.datasources.get(datasource._id!)
builderSocket?.emitDatasourceUpdate(ctx, updatedDatasource) builderSocket?.emitDatasourceUpdate(ctx, updatedDatasource)
return tableToSave return tableToSave
@ -354,7 +354,7 @@ export async function destroy(ctx: UserCtx) {
// Since tables are stored inside datasources, we need to notify clients // Since tables are stored inside datasources, we need to notify clients
// that the datasource definition changed // that the datasource definition changed
const updatedDatasource = await db.get(datasource._id) const updatedDatasource = await sdk.datasources.get(datasource._id!)
builderSocket?.emitDatasourceUpdate(ctx, updatedDatasource) builderSocket?.emitDatasourceUpdate(ctx, updatedDatasource)
return tableToDelete return tableToDelete

View file

@ -15,7 +15,7 @@ import { isEqual } from "lodash"
import { cloneDeep } from "lodash/fp" import { cloneDeep } from "lodash/fp"
import sdk from "../../../sdk" import sdk from "../../../sdk"
function checkAutoColumns(table: Table, oldTable: Table) { function checkAutoColumns(table: Table, oldTable?: Table) {
if (!table.schema) { if (!table.schema) {
return table return table
} }
@ -46,7 +46,7 @@ export async function save(ctx: any) {
// if the table obj had an _id then it will have been retrieved // if the table obj had an _id then it will have been retrieved
let oldTable let oldTable
if (ctx.request.body && ctx.request.body._id) { if (ctx.request.body && ctx.request.body._id) {
oldTable = await db.get(ctx.request.body._id) oldTable = await sdk.tables.getTable(ctx.request.body._id)
} }
// check all types are correct // check all types are correct
@ -70,8 +70,8 @@ export async function save(ctx: any) {
if (oldTable && oldTable.schema) { if (oldTable && oldTable.schema) {
for (let propKey of Object.keys(tableToSave.schema)) { for (let propKey of Object.keys(tableToSave.schema)) {
let oldColumn = oldTable.schema[propKey] let oldColumn = oldTable.schema[propKey]
if (oldColumn && oldColumn.type === "internal") { if (oldColumn && oldColumn.type === FieldTypes.INTERNAL) {
oldColumn.type = "auto" oldColumn.type = FieldTypes.AUTO
} }
} }
} }
@ -138,7 +138,7 @@ export async function save(ctx: any) {
export async function destroy(ctx: any) { export async function destroy(ctx: any) {
const db = context.getAppDB() const db = context.getAppDB()
const tableToDelete = await db.get(ctx.params.tableId) const tableToDelete = await sdk.tables.getTable(ctx.params.tableId)
// Delete all rows for that table // Delete all rows for that table
const rowsData = await db.allDocs( const rowsData = await db.allDocs(
@ -160,7 +160,7 @@ export async function destroy(ctx: any) {
}) })
// don't remove the table itself until very end // don't remove the table itself until very end
await db.remove(tableToDelete._id, tableToDelete._rev) await db.remove(tableToDelete._id!, tableToDelete._rev)
// remove table search index // remove table search index
if (!env.isTest() || env.COUCH_DB_URL) { if (!env.isTest() || env.COUCH_DB_URL) {

View file

@ -36,8 +36,8 @@ export async function updateMetadata(ctx: UserCtx) {
export async function destroyMetadata(ctx: UserCtx) { export async function destroyMetadata(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
try { try {
const dbUser = await db.get(ctx.params.id) const dbUser = await sdk.users.get(ctx.params.id)
await db.remove(dbUser._id, dbUser._rev) await db.remove(dbUser._id!, dbUser._rev)
} catch (err) { } catch (err) {
// error just means the global user has no config in this app // error just means the global user has no config in this app
} }
@ -60,7 +60,7 @@ export async function setFlag(ctx: UserCtx) {
const db = context.getAppDB() const db = context.getAppDB()
let doc let doc
try { try {
doc = await db.get(flagDocId) doc = await db.get<any>(flagDocId)
} catch (err) { } catch (err) {
doc = { _id: flagDocId } doc = { _id: flagDocId }
} }

View file

@ -27,7 +27,8 @@ export async function save(ctx: Ctx) {
const db = context.getAppDB() const db = context.getAppDB()
const { originalName, ...viewToSave } = ctx.request.body const { originalName, ...viewToSave } = ctx.request.body
const existingTable = await db.get(ctx.request.body.tableId) const existingTable = await sdk.tables.getTable(ctx.request.body.tableId)
existingTable.views ??= {}
const table = cloneDeep(existingTable) const table = cloneDeep(existingTable)
const groupByField: any = Object.values(table.schema).find( const groupByField: any = Object.values(table.schema).find(
@ -120,8 +121,8 @@ export async function destroy(ctx: Ctx) {
const db = context.getAppDB() const db = context.getAppDB()
const viewName = decodeURIComponent(ctx.params.viewName) const viewName = decodeURIComponent(ctx.params.viewName)
const view = await deleteView(viewName) const view = await deleteView(viewName)
const table = await db.get(view.meta.tableId) const table = await sdk.tables.getTable(view.meta.tableId)
delete table.views[viewName] delete table.views![viewName]
await db.put(table) await db.put(table)
await events.view.deleted(view) await events.view.deleted(view)

View file

@ -13,7 +13,7 @@ import { Database } from "@budibase/types"
export async function getView(viewName: string) { export async function getView(viewName: string) {
const db = context.getAppDB() const db = context.getAppDB()
if (env.SELF_HOSTED) { if (env.SELF_HOSTED) {
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
return designDoc.views[viewName] return designDoc.views[viewName]
} else { } else {
// This is a table view, don't read the view from the DB // This is a table view, don't read the view from the DB
@ -22,7 +22,7 @@ export async function getView(viewName: string) {
} }
try { try {
const viewDoc = await db.get(generateMemoryViewID(viewName)) const viewDoc = await db.get<any>(generateMemoryViewID(viewName))
return viewDoc.view return viewDoc.view
} catch (err: any) { } catch (err: any) {
// Return null when PouchDB doesn't found the view // Return null when PouchDB doesn't found the view
@ -39,7 +39,7 @@ export async function getViews() {
const db = context.getAppDB() const db = context.getAppDB()
const response = [] const response = []
if (env.SELF_HOSTED) { if (env.SELF_HOSTED) {
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
for (let name of Object.keys(designDoc.views)) { for (let name of Object.keys(designDoc.views)) {
// Only return custom views, not built ins // Only return custom views, not built ins
const viewNames = Object.values(ViewName) as string[] const viewNames = Object.values(ViewName) as string[]
@ -76,7 +76,7 @@ export async function saveView(
) { ) {
const db = context.getAppDB() const db = context.getAppDB()
if (env.SELF_HOSTED) { if (env.SELF_HOSTED) {
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
designDoc.views = { designDoc.views = {
...designDoc.views, ...designDoc.views,
[viewName]: viewTemplate, [viewName]: viewTemplate,
@ -96,9 +96,9 @@ export async function saveView(
tableId: viewTemplate.meta.tableId, tableId: viewTemplate.meta.tableId,
} }
try { try {
const old = await db.get(id) const old = await db.get<any>(id)
if (originalId) { if (originalId) {
const originalDoc = await db.get(originalId) const originalDoc = await db.get<any>(originalId)
await db.remove(originalDoc._id, originalDoc._rev) await db.remove(originalDoc._id, originalDoc._rev)
} }
if (old && old._rev) { if (old && old._rev) {
@ -114,14 +114,14 @@ export async function saveView(
export async function deleteView(viewName: string) { export async function deleteView(viewName: string) {
const db = context.getAppDB() const db = context.getAppDB()
if (env.SELF_HOSTED) { if (env.SELF_HOSTED) {
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
const view = designDoc.views[viewName] const view = designDoc.views[viewName]
delete designDoc.views[viewName] delete designDoc.views[viewName]
await db.put(designDoc) await db.put(designDoc)
return view return view
} else { } else {
const id = generateMemoryViewID(viewName) const id = generateMemoryViewID(viewName)
const viewDoc = await db.get(id) const viewDoc = await db.get<any>(id)
await db.remove(viewDoc._id, viewDoc._rev) await db.remove(viewDoc._id, viewDoc._rev)
return viewDoc.view return viewDoc.view
} }
@ -129,7 +129,7 @@ export async function deleteView(viewName: string) {
export async function migrateToInMemoryView(db: Database, viewName: string) { export async function migrateToInMemoryView(db: Database, viewName: string) {
// delete the view initially // delete the view initially
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
// run the view back through the view builder to update it // run the view back through the view builder to update it
const view = viewBuilder(designDoc.views[viewName].meta) const view = viewBuilder(designDoc.views[viewName].meta)
delete designDoc.views[viewName] delete designDoc.views[viewName]
@ -138,15 +138,15 @@ export async function migrateToInMemoryView(db: Database, viewName: string) {
} }
export async function migrateToDesignView(db: Database, viewName: string) { export async function migrateToDesignView(db: Database, viewName: string) {
let view = await db.get(generateMemoryViewID(viewName)) let view = await db.get<any>(generateMemoryViewID(viewName))
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
designDoc.views[viewName] = viewBuilder(view.view.meta) designDoc.views[viewName] = viewBuilder(view.view.meta)
await db.put(designDoc) await db.put(designDoc)
await db.remove(view._id, view._rev) await db.remove(view._id, view._rev)
} }
export async function getFromDesignDoc(db: Database, viewName: string) { export async function getFromDesignDoc(db: Database, viewName: string) {
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
let view = designDoc.views[viewName] let view = designDoc.views[viewName]
if (view == null) { if (view == null) {
throw { status: 404, message: "Unable to get view" } throw { status: 404, message: "Unable to get view" }
@ -155,7 +155,7 @@ export async function getFromDesignDoc(db: Database, viewName: string) {
} }
export async function getFromMemoryDoc(db: Database, viewName: string) { export async function getFromMemoryDoc(db: Database, viewName: string) {
let view = await db.get(generateMemoryViewID(viewName)) let view = await db.get<any>(generateMemoryViewID(viewName))
if (view) { if (view) {
view = view.view view = view.view
} else { } else {

View file

@ -77,7 +77,7 @@ export async function trigger(ctx: BBContext) {
if (webhook.bodySchema) { if (webhook.bodySchema) {
validate(ctx.request.body, webhook.bodySchema) validate(ctx.request.body, webhook.bodySchema)
} }
const target = await db.get(webhook.action.target) const target = await db.get<Automation>(webhook.action.target)
if (webhook.action.type === WebhookActionType.AUTOMATION) { if (webhook.action.type === WebhookActionType.AUTOMATION) {
// trigger with both the pure request and then expand it // trigger with both the pure request and then expand it
// incase the user has produced a schema to bind to // incase the user has produced a schema to bind to

View file

@ -8,7 +8,12 @@ import { db as dbCore, context } from "@budibase/backend-core"
import { getAutomationMetadataParams } from "../db/utils" import { getAutomationMetadataParams } from "../db/utils"
import { cloneDeep } from "lodash/fp" import { cloneDeep } from "lodash/fp"
import { quotas } from "@budibase/pro" import { quotas } from "@budibase/pro"
import { Automation, AutomationJob, WebhookActionType } from "@budibase/types" import {
Automation,
AutomationJob,
Webhook,
WebhookActionType,
} from "@budibase/types"
import sdk from "../sdk" import sdk from "../sdk"
const REBOOT_CRON = "@reboot" const REBOOT_CRON = "@reboot"
@ -206,13 +211,13 @@ export async function checkForWebhooks({ oldAuto, newAuto }: any) {
try { try {
let db = context.getAppDB() let db = context.getAppDB()
// need to get the webhook to get the rev // need to get the webhook to get the rev
const webhook = await db.get(oldTrigger.webhookId) const webhook = await db.get<Webhook>(oldTrigger.webhookId)
// might be updating - reset the inputs to remove the URLs // might be updating - reset the inputs to remove the URLs
if (newTrigger) { if (newTrigger) {
delete newTrigger.webhookId delete newTrigger.webhookId
newTrigger.inputs = {} newTrigger.inputs = {}
} }
await sdk.automations.webhook.destroy(webhook._id, webhook._rev) await sdk.automations.webhook.destroy(webhook._id!, webhook._rev!)
} catch (err) { } catch (err) {
// don't worry about not being able to delete, if it doesn't exist all good // don't worry about not being able to delete, if it doesn't exist all good
} }

View file

@ -182,7 +182,7 @@ class LinkController {
}) })
// if 1:N, ensure that this ID is not already attached to another record // if 1:N, ensure that this ID is not already attached to another record
const linkedTable = await this._db.get(field.tableId) const linkedTable = await this._db.get<Table>(field.tableId)
const linkedSchema = linkedTable.schema[field.fieldName!] const linkedSchema = linkedTable.schema[field.fieldName!]
// We need to map the global users to metadata in each app for relationships // We need to map the global users to metadata in each app for relationships
@ -311,7 +311,7 @@ class LinkController {
}) })
) )
// remove schema from other table // remove schema from other table
let linkedTable = await this._db.get(field.tableId) let linkedTable = await this._db.get<Table>(field.tableId)
if (field.fieldName) { if (field.fieldName) {
delete linkedTable.schema[field.fieldName] delete linkedTable.schema[field.fieldName]
} }
@ -337,7 +337,7 @@ class LinkController {
// table for some reason // table for some reason
let linkedTable let linkedTable
try { try {
linkedTable = await this._db.get(field.tableId) linkedTable = await this._db.get<Table>(field.tableId)
} catch (err) { } catch (err) {
/* istanbul ignore next */ /* istanbul ignore next */
continue continue
@ -416,7 +416,7 @@ class LinkController {
const field = schema[fieldName] const field = schema[fieldName]
try { try {
if (field.type === FieldTypes.LINK && field.fieldName) { if (field.type === FieldTypes.LINK && field.fieldName) {
const linkedTable = await this._db.get(field.tableId) const linkedTable = await this._db.get<Table>(field.tableId)
delete linkedTable.schema[field.fieldName] delete linkedTable.schema[field.fieldName]
await this._db.put(linkedTable) await this._db.put(linkedTable)
} }

View file

@ -22,7 +22,7 @@ const SCREEN_PREFIX = DocumentType.SCREEN + SEPARATOR
*/ */
export async function createLinkView() { export async function createLinkView() {
const db = context.getAppDB() const db = context.getAppDB()
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
const view = { const view = {
map: function (doc: LinkDocument) { map: function (doc: LinkDocument) {
// everything in this must remain constant as its going to Pouch, no external variables // everything in this must remain constant as its going to Pouch, no external variables
@ -58,7 +58,7 @@ export async function createLinkView() {
export async function createRoutingView() { export async function createRoutingView() {
const db = context.getAppDB() const db = context.getAppDB()
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
const view = { const view = {
// if using variables in a map function need to inject them before use // if using variables in a map function need to inject them before use
map: `function(doc) { map: `function(doc) {
@ -79,7 +79,7 @@ export async function createRoutingView() {
async function searchIndex(indexName: string, fnString: string) { async function searchIndex(indexName: string, fnString: string) {
const db = context.getAppDB() const db = context.getAppDB()
const designDoc = await db.get("_design/database") const designDoc = await db.get<any>("_design/database")
designDoc.indexes = { designDoc.indexes = {
[indexName]: { [indexName]: {
index: fnString, index: fnString,

View file

@ -10,7 +10,7 @@ import {
setDebounce, setDebounce,
} from "../utilities/redis" } from "../utilities/redis"
import { db as dbCore, cache } from "@budibase/backend-core" import { db as dbCore, cache } from "@budibase/backend-core"
import { UserCtx, Database } from "@budibase/types" import { UserCtx, Database, App } from "@budibase/types"
const DEBOUNCE_TIME_SEC = 30 const DEBOUNCE_TIME_SEC = 30
@ -51,7 +51,7 @@ async function updateAppUpdatedAt(ctx: UserCtx) {
} }
await dbCore.doWithDB(appId, async (db: Database) => { await dbCore.doWithDB(appId, async (db: Database) => {
try { try {
const metadata = await db.get(DocumentType.APP_METADATA) const metadata = await db.get<any>(DocumentType.APP_METADATA)
metadata.updatedAt = new Date().toISOString() metadata.updatedAt = new Date().toISOString()
metadata.updatedBy = getGlobalIDFromUserMetadataID(ctx.user?.userId!) metadata.updatedBy = getGlobalIDFromUserMetadataID(ctx.user?.userId!)

View file

@ -37,7 +37,7 @@ async function syncUsersToApp(
let metadata let metadata
try { try {
metadata = await db.get(metadataId) metadata = await db.get<any>(metadataId)
} catch (err: any) { } catch (err: any) {
if (err.status !== 404) { if (err.status !== 404) {
throw err throw err

View file

@ -62,7 +62,7 @@ export async function get(
opts?: { enriched: boolean } opts?: { enriched: boolean }
): Promise<Datasource> { ): Promise<Datasource> {
const appDb = context.getAppDB() const appDb = context.getAppDB()
const datasource = await appDb.get(datasourceId) const datasource = await appDb.get<Datasource>(datasourceId)
if (opts?.enriched) { if (opts?.enriched) {
return (await enrichDatasourceWithValues(datasource)).datasource return (await enrichDatasourceWithValues(datasource)).datasource
} else { } else {
@ -72,7 +72,7 @@ export async function get(
export async function getWithEnvVars(datasourceId: string) { export async function getWithEnvVars(datasourceId: string) {
const appDb = context.getAppDB() const appDb = context.getAppDB()
const datasource = await appDb.get(datasourceId) const datasource = await appDb.get<Datasource>(datasourceId)
return enrichDatasourceWithValues(datasource) return enrichDatasourceWithValues(datasource)
} }

View file

@ -11,7 +11,7 @@ import {
} from "../../../../db/utils" } from "../../../../db/utils"
import { getGlobalUsersFromMetadata } from "../../../../utilities/global" import { getGlobalUsersFromMetadata } from "../../../../utilities/global"
import { outputProcessing } from "../../../../utilities/rowProcessor" import { outputProcessing } from "../../../../utilities/rowProcessor"
import { Database, Row } from "@budibase/types" import { Database, Row, Table } from "@budibase/types"
import { cleanExportRows } from "../utils" import { cleanExportRows } from "../utils"
import { import {
Format, Format,
@ -37,7 +37,6 @@ export async function search(options: SearchParams) {
return { rows: await fetch(tableId) } return { rows: await fetch(tableId) }
} }
const db = context.getAppDB()
const { paginate, query } = options const { paginate, query } = options
const params: InternalSearchParams<any> = { const params: InternalSearchParams<any> = {
@ -53,7 +52,7 @@ export async function search(options: SearchParams) {
let table let table
if (params.sort && !params.sortType) { if (params.sort && !params.sortType) {
table = await db.get(tableId) table = await sdk.tables.getTable(tableId)
const schema = table.schema const schema = table.schema
const sortField = schema[params.sort] const sortField = schema[params.sort]
params.sortType = sortField.type === "number" ? "number" : "string" params.sortType = sortField.type === "number" ? "number" : "string"
@ -72,7 +71,7 @@ export async function search(options: SearchParams) {
if (tableId === InternalTables.USER_METADATA) { if (tableId === InternalTables.USER_METADATA) {
response.rows = await getGlobalUsersFromMetadata(response.rows) response.rows = await getGlobalUsersFromMetadata(response.rows)
} }
table = table || (await db.get(tableId)) table = table || (await sdk.tables.getTable(tableId))
response.rows = await outputProcessing(table, response.rows) response.rows = await outputProcessing(table, response.rows)
} }
@ -84,7 +83,7 @@ export async function exportRows(
): Promise<ExportRowsResult> { ): Promise<ExportRowsResult> {
const { tableId, format, rowIds, columns, query } = options const { tableId, format, rowIds, columns, query } = options
const db = context.getAppDB() const db = context.getAppDB()
const table = await db.get(tableId) const table = await sdk.tables.getTable(tableId)
let result let result
if (rowIds) { if (rowIds) {
@ -140,7 +139,7 @@ export async function exportRows(
export async function fetch(tableId: string) { export async function fetch(tableId: string) {
const db = context.getAppDB() const db = context.getAppDB()
let table = await db.get(tableId) let table = await sdk.tables.getTable(tableId)
let rows = await getRawTableData(db, tableId) let rows = await getRawTableData(db, tableId)
const result = await outputProcessing(table, rows) const result = await outputProcessing(table, rows)
return result return result
@ -193,12 +192,13 @@ export async function fetchView(
let rows let rows
if (!calculation) { if (!calculation) {
response.rows = response.rows.map(row => row.doc) response.rows = response.rows.map(row => row.doc)
let table let table: Table
try { try {
table = await db.get(viewInfo.meta.tableId) table = await sdk.tables.getTable(viewInfo.meta.tableId)
} catch (err) { } catch (err) {
/* istanbul ignore next */ /* istanbul ignore next */
table = { table = {
name: "",
schema: {}, schema: {},
} }
} }

View file

@ -0,0 +1,7 @@
import { context } from "@budibase/backend-core"
import { User } from "@budibase/types"
export function get(userId: string) {
const db = context.getAppDB()
return db.get<User>(userId)
}

View file

@ -1,7 +1,9 @@
import * as utils from "./utils" import * as utils from "./utils"
import * as sessions from "./sessions" import * as sessions from "./sessions"
import * as crud from "./crud"
export default { export default {
...utils, ...utils,
...crud,
sessions, sessions,
} }

View file

@ -11,6 +11,7 @@ import { cloneDeep } from "lodash/fp"
import { isSQL } from "../integrations/utils" import { isSQL } from "../integrations/utils"
import { interpolateSQL } from "../integrations/queries/sql" import { interpolateSQL } from "../integrations/queries/sql"
import { Query } from "@budibase/types"
class QueryRunner { class QueryRunner {
datasource: any datasource: any
@ -167,7 +168,7 @@ class QueryRunner {
async runAnotherQuery(queryId: string, parameters: any) { async runAnotherQuery(queryId: string, parameters: any) {
const db = context.getAppDB() const db = context.getAppDB()
const query = await db.get(queryId) const query = await db.get<Query>(queryId)
const datasource = await sdk.datasources.get(query.datasourceId, { const datasource = await sdk.datasources.get(query.datasourceId, {
enriched: true, enriched: true,
}) })

View file

@ -90,7 +90,7 @@ export async function getCachedSelf(ctx: UserCtx, appId: string) {
export async function getRawGlobalUser(userId: string) { export async function getRawGlobalUser(userId: string) {
const db = tenancy.getGlobalDB() const db = tenancy.getGlobalDB()
return db.get(getGlobalIDFromUserMetadataID(userId)) return db.get<User>(getGlobalIDFromUserMetadataID(userId))
} }
export async function getGlobalUser(userId: string) { export async function getGlobalUser(userId: string) {

View file

@ -41,7 +41,7 @@ export async function updateEntityMetadata(
// read it to see if it exists, we'll overwrite it no matter what // read it to see if it exists, we'll overwrite it no matter what
let rev, metadata: Document let rev, metadata: Document
try { try {
const oldMetadata = await db.get(id) const oldMetadata = await db.get<any>(id)
rev = oldMetadata._rev rev = oldMetadata._rev
metadata = updateFn(oldMetadata) metadata = updateFn(oldMetadata)
} catch (err) { } catch (err) {
@ -75,7 +75,7 @@ export async function deleteEntityMetadata(type: string, entityId: string) {
const id = generateMetadataID(type, entityId) const id = generateMetadataID(type, entityId)
let rev let rev
try { try {
const metadata = await db.get(id) const metadata = await db.get<any>(id)
if (metadata) { if (metadata) {
rev = metadata._rev rev = metadata._rev
} }

View file

@ -1,6 +1,6 @@
import { sendEmail as sendEmailFn } from "../../../utilities/email" import { sendEmail as sendEmailFn } from "../../../utilities/email"
import { tenancy } from "@budibase/backend-core" import { tenancy } from "@budibase/backend-core"
import { BBContext } from "@budibase/types" import { BBContext, User } from "@budibase/types"
export async function sendEmail(ctx: BBContext) { export async function sendEmail(ctx: BBContext) {
let { let {
@ -16,10 +16,10 @@ export async function sendEmail(ctx: BBContext) {
automation, automation,
invite, invite,
} = ctx.request.body } = ctx.request.body
let user let user: any
if (userId) { if (userId) {
const db = tenancy.getGlobalDB() const db = tenancy.getGlobalDB()
user = await db.get(userId) user = await db.get<User>(userId)
} }
const response = await sendEmailFn(email, purpose, { const response = await sendEmailFn(email, purpose, {
workspaceId, workspaceId,

View file

@ -35,7 +35,7 @@ export async function find(ctx: BBContext) {
const appId = ctx.params.appId const appId = ctx.params.appId
await context.doInAppContext(dbCore.getDevAppID(appId), async () => { await context.doInAppContext(dbCore.getDevAppID(appId), async () => {
const db = context.getAppDB() const db = context.getAppDB()
const app = await db.get(dbCore.DocumentType.APP_METADATA) const app = await db.get<App>(dbCore.DocumentType.APP_METADATA)
ctx.body = { ctx.body = {
roles: await roles.getAllRoles(), roles: await roles.getAllRoles(),
name: app.name, name: app.name,

View file

@ -44,7 +44,7 @@ export async function generateAPIKey(ctx: any) {
const id = dbCore.generateDevInfoID(userId) const id = dbCore.generateDevInfoID(userId)
let devInfo let devInfo
try { try {
devInfo = await db.get(id) devInfo = await db.get<any>(id)
} catch (err) { } catch (err) {
devInfo = { _id: id, userId } devInfo = { _id: id, userId }
} }

View file

@ -412,7 +412,7 @@ export const inviteAccept = async (
const saved = await userSdk.save(request) const saved = await userSdk.save(request)
const db = tenancy.getGlobalDB() const db = tenancy.getGlobalDB()
const user = await db.get(saved._id) const user = await db.get<User>(saved._id)
await events.user.inviteAccepted(user) await events.user.inviteAccepted(user)
return saved return saved
}) })