2023-07-31 12:03:03 +02:00
|
|
|
import { Ctx, Row } from "@budibase/types"
|
|
|
|
import * as utils from "../db/utils"
|
|
|
|
import sdk from "../sdk"
|
|
|
|
import { db } from "@budibase/backend-core"
|
2023-07-31 13:17:54 +02:00
|
|
|
import { Next } from "koa"
|
2023-08-08 14:19:22 +02:00
|
|
|
import { getTableId } from "../api/controllers/row/utils"
|
2023-07-31 12:03:03 +02:00
|
|
|
|
2023-07-31 13:17:54 +02:00
|
|
|
export default async (ctx: Ctx<Row>, next: Next) => {
|
2023-07-31 12:03:03 +02:00
|
|
|
const { body } = ctx.request
|
2023-08-08 14:19:22 +02:00
|
|
|
let { _viewId: viewId } = body
|
2023-07-31 14:08:31 +02:00
|
|
|
|
2023-08-08 14:19:22 +02:00
|
|
|
const possibleViewId = getTableId(ctx)
|
|
|
|
if (utils.isViewID(possibleViewId)) {
|
|
|
|
viewId = possibleViewId
|
|
|
|
}
|
2023-08-04 17:58:40 +02:00
|
|
|
|
|
|
|
// nothing to do, it is not a view (just a table ID)
|
2023-08-08 14:19:22 +02:00
|
|
|
if (!viewId) {
|
2023-08-04 17:58:40 +02:00
|
|
|
return next()
|
2023-07-31 12:03:03 +02:00
|
|
|
}
|
|
|
|
|
2023-08-08 14:19:22 +02:00
|
|
|
const { tableId } = utils.extractViewInfoFromID(viewId)
|
|
|
|
|
|
|
|
// don't need to trim delete requests
|
2023-08-08 14:43:13 +02:00
|
|
|
if (ctx?.method?.toLowerCase() !== "delete") {
|
2023-08-14 13:10:16 +02:00
|
|
|
await trimViewFields(ctx.request.body, viewId)
|
2023-08-08 14:19:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
ctx.params.sourceId = tableId
|
2023-07-31 12:03:03 +02:00
|
|
|
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2023-08-14 12:44:10 +02:00
|
|
|
// have to mutate the koa context, can't return
|
2023-07-31 12:03:03 +02:00
|
|
|
export async function trimViewFields<T extends Row>(
|
2023-08-14 12:44:10 +02:00
|
|
|
body: Row,
|
2023-08-14 13:10:16 +02:00
|
|
|
viewId: string
|
2023-08-14 12:44:10 +02:00
|
|
|
): Promise<void> {
|
2023-07-31 12:03:03 +02:00
|
|
|
const view = await sdk.views.get(viewId)
|
2023-08-14 12:44:10 +02:00
|
|
|
const allowedKeys = [
|
2023-08-14 13:10:16 +02:00
|
|
|
...Object.keys(view?.schema || {}),
|
2023-07-31 12:03:03 +02:00
|
|
|
...db.CONSTANT_EXTERNAL_ROW_COLS,
|
|
|
|
...db.CONSTANT_INTERNAL_ROW_COLS,
|
2023-08-14 12:44:10 +02:00
|
|
|
]
|
|
|
|
// have to mutate the context, can't update reference
|
|
|
|
const toBeRemoved = Object.keys(body).filter(
|
|
|
|
key => !allowedKeys.includes(key)
|
|
|
|
)
|
|
|
|
for (let removeKey of toBeRemoved) {
|
|
|
|
delete body[removeKey]
|
2023-07-31 12:03:03 +02:00
|
|
|
}
|
|
|
|
}
|