1
0
Fork 0
mirror of synced 2024-09-25 22:01:43 +12:00
budibase/packages/server/src/utilities/rowProcessor/bbReferenceProcessor.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-09-15 21:21:10 +12:00
import { cache } from "@budibase/backend-core"
import { utils } from "@budibase/shared-core"
2023-09-15 23:31:22 +12:00
import { FieldSubtype } from "@budibase/types"
2023-09-15 22:07:25 +12:00
import { InvalidBBRefError } from "./errors"
2023-09-15 20:33:36 +12:00
2023-09-15 21:21:10 +12:00
export async function processInputBBReferences(
2023-09-15 22:07:25 +12:00
value: string | string[] | { _id: string } | { _id: string }[],
2023-09-15 20:33:36 +12:00
subtype: FieldSubtype
2023-09-15 22:07:25 +12:00
): Promise<string> {
const result: string[] = []
2023-09-15 21:21:10 +12:00
switch (subtype) {
case FieldSubtype.USER:
2023-09-15 22:07:25 +12:00
if (Array.isArray(value)) {
result.push(...value.map(x => (typeof x === "string" ? x : x._id)))
} else if (typeof value !== "string") {
result.push(value._id)
} else {
result.push(...value.split(",").map((id: string) => id.trim()))
}
const { notFoundIds } = await cache.user.getUsers(result)
if (notFoundIds?.length) {
throw new InvalidBBRefError(notFoundIds[0], FieldSubtype.USER)
2023-09-15 21:21:10 +12:00
}
2023-09-15 21:21:10 +12:00
break
default:
2023-09-15 22:07:25 +12:00
throw utils.unreachable(subtype)
2023-09-15 21:21:10 +12:00
}
2023-09-15 22:07:25 +12:00
return result.join(",")
2023-09-15 21:21:10 +12:00
}
2023-09-15 23:31:22 +12:00
export async function processOutputBBReferences(
value: string,
subtype: FieldSubtype
) {
2023-09-15 23:47:08 +12:00
if (typeof value !== "string") {
2023-09-19 23:17:07 +12:00
// Already processed or nothing to process
2023-09-15 23:47:08 +12:00
return value
}
const ids = value.split(",").filter(id => !!id)
2023-09-19 23:17:07 +12:00
2023-09-15 23:31:22 +12:00
switch (subtype) {
case FieldSubtype.USER:
const { users } = await cache.user.getUsers(ids)
return users
2023-09-15 23:31:22 +12:00
default:
throw utils.unreachable(subtype)
}
}