Validate view schema on upsert

This commit is contained in:
Adria Navarro 2024-05-24 16:07:07 +02:00
parent a0c2843236
commit 28137f9500
2 changed files with 33 additions and 3 deletions

View File

@ -141,7 +141,7 @@ describe.each([
type: SortType.STRING, type: SortType.STRING,
}, },
schema: { schema: {
name: { Price: {
visible: true, visible: true,
}, },
}, },
@ -150,7 +150,11 @@ describe.each([
expect(res).toEqual({ expect(res).toEqual({
...newView, ...newView,
schema: newView.schema, schema: {
Price: {
visible: true,
},
},
id: expect.any(String), id: expect.any(String),
version: 2, version: 2,
}) })

View File

@ -2,10 +2,11 @@ import {
RenameColumn, RenameColumn,
TableSchema, TableSchema,
View, View,
ViewUIFieldMetadata,
ViewV2, ViewV2,
ViewV2Enriched, ViewV2Enriched,
} from "@budibase/types" } from "@budibase/types"
import { db as dbCore } from "@budibase/backend-core" import { HTTPError, db as dbCore } from "@budibase/backend-core"
import { cloneDeep } from "lodash" import { cloneDeep } from "lodash"
import * as utils from "../../../db/utils" import * as utils from "../../../db/utils"
@ -13,6 +14,7 @@ import { isExternalTableID } from "../../../integrations/utils"
import * as internal from "./internal" import * as internal from "./internal"
import * as external from "./external" import * as external from "./external"
import sdk from "../../../sdk"
function pickApi(tableId: any) { function pickApi(tableId: any) {
if (isExternalTableID(tableId)) { if (isExternalTableID(tableId)) {
@ -31,14 +33,38 @@ export async function getEnriched(viewId: string): Promise<ViewV2Enriched> {
return pickApi(tableId).getEnriched(viewId) return pickApi(tableId).getEnriched(viewId)
} }
async function guardViewSchema(
tableId: string,
schema?: Record<string, ViewUIFieldMetadata>
) {
if (!schema || !Object.keys(schema).length) {
return
}
const table = await sdk.tables.getTable(tableId)
if (schema) {
for (const field of Object.keys(schema)) {
if (!table.schema[field]) {
throw new HTTPError(
`Field "${field}" is not valid for the requested table`,
400
)
}
}
}
}
export async function create( export async function create(
tableId: string, tableId: string,
viewRequest: Omit<ViewV2, "id" | "version"> viewRequest: Omit<ViewV2, "id" | "version">
): Promise<ViewV2> { ): Promise<ViewV2> {
await guardViewSchema(tableId, viewRequest.schema)
return pickApi(tableId).create(tableId, viewRequest) return pickApi(tableId).create(tableId, viewRequest)
} }
export async function update(tableId: string, view: ViewV2): Promise<ViewV2> { export async function update(tableId: string, view: ViewV2): Promise<ViewV2> {
await guardViewSchema(tableId, view.schema)
return pickApi(tableId).update(tableId, view) return pickApi(tableId).update(tableId, view)
} }