Update user column data on import

This commit is contained in:
Adria Navarro 2024-10-22 10:23:27 +02:00
parent 2795eca672
commit 87dbe66ccc
1 changed files with 70 additions and 0 deletions

View File

@ -23,6 +23,7 @@ import {
cache, cache,
context, context,
db as dbCore, db as dbCore,
docIds,
env as envCore, env as envCore,
ErrorCode, ErrorCode,
events, events,
@ -54,6 +55,10 @@ import {
DuplicateAppResponse, DuplicateAppResponse,
UpdateAppRequest, UpdateAppRequest,
UpdateAppResponse, UpdateAppResponse,
Database,
FieldType,
BBReferenceFieldSubType,
Row,
} from "@budibase/types" } from "@budibase/types"
import { BASE_LAYOUT_PROP_IDS } from "../../constants/layouts" import { BASE_LAYOUT_PROP_IDS } from "../../constants/layouts"
import sdk from "../../sdk" import sdk from "../../sdk"
@ -279,6 +284,11 @@ async function performAppCreate(ctx: UserCtx<CreateAppRequest, App>) {
const instance = await createInstance(appId, instanceConfig) const instance = await createInstance(appId, instanceConfig)
const db = context.getAppDB() const db = context.getAppDB()
const isTemplate = instanceConfig.templateString
if (!isTemplate) {
await updateUserColumns(appId, db, ctx.user._id!)
}
const newApplication: App = { const newApplication: App = {
_id: DocumentType.APP_METADATA, _id: DocumentType.APP_METADATA,
_rev: undefined, _rev: undefined,
@ -375,6 +385,66 @@ async function performAppCreate(ctx: UserCtx<CreateAppRequest, App>) {
}) })
} }
async function updateUserColumns(
appId: string,
db: Database,
toUserId: string
) {
await context.doInAppContext(appId, async () => {
const allTables = await sdk.tables.getAllTables()
const tablesWithUserColumns = []
for (const table of allTables) {
const userColumns = Object.values(table.schema).filter(
f =>
(f.type === FieldType.BB_REFERENCE ||
f.type === FieldType.BB_REFERENCE_SINGLE) &&
f.subtype === BBReferenceFieldSubType.USER
)
if (!userColumns.length) {
continue
}
tablesWithUserColumns.push({
tableId: table._id!,
columns: userColumns.map(c => c.name),
})
}
const docsToUpdate = []
for (const { tableId, columns } of tablesWithUserColumns) {
const docs = await db.allDocs<Row>(
docIds.getRowParams(tableId, null, { include_docs: true })
)
const rows = docs.rows.map(d => d.doc!)
for (const row of rows) {
let shouldUpdate = false
const updatedColumns = columns.reduce<Row>((newColumns, column) => {
if (row[column]) {
shouldUpdate = true
if (Array.isArray(row[column])) {
newColumns[column] = row[column]?.map(() => toUserId)
} else if (row[column]) {
newColumns[column] = toUserId
}
}
return newColumns
}, {})
if (shouldUpdate) {
docsToUpdate.push({
...row,
...updatedColumns,
})
}
}
}
await db.bulkDocs(docsToUpdate)
})
}
async function creationEvents(request: any, app: App) { async function creationEvents(request: any, app: App) {
let creationFns: ((app: App) => Promise<void>)[] = [] let creationFns: ((app: App) => Promise<void>)[] = []