1
0
Fork 0
mirror of synced 2024-09-25 22:01:43 +12:00
budibase/packages/server/src/utilities/rowProcessor/bbReferenceProcessor.ts
Adria Navarro 753cb442c2 Allow edit
2023-10-04 17:55:23 +02:00

74 lines
1.8 KiB
TypeScript

import { cache } from "@budibase/backend-core"
import { utils } from "@budibase/shared-core"
import { FieldSubtype } from "@budibase/types"
import { InvalidBBRefError } from "./errors"
export async function processInputBBReferences(
value: string | string[] | { _id: string } | { _id: string }[],
subtype: FieldSubtype
): Promise<string | null> {
const referenceIds: string[] = []
if (Array.isArray(value)) {
referenceIds.push(
...value.map(idOrDoc =>
typeof idOrDoc === "string" ? idOrDoc : idOrDoc._id
)
)
} else if (typeof value !== "string") {
referenceIds.push(value._id)
} else {
referenceIds.push(
...value
.split(",")
.filter(x => x)
.map((id: string) => id.trim())
)
}
switch (subtype) {
case FieldSubtype.USER:
case FieldSubtype.USERS:
const { notFoundIds } = await cache.user.getUsers(referenceIds)
if (notFoundIds?.length) {
throw new InvalidBBRefError(notFoundIds[0], FieldSubtype.USER)
}
return referenceIds.join(",") || null
default:
throw utils.unreachable(subtype)
}
}
export async function processOutputBBReferences(
value: string,
subtype: FieldSubtype
) {
if (typeof value !== "string") {
// Already processed or nothing to process
return value || undefined
}
const ids = value.split(",").filter(id => !!id)
switch (subtype) {
case FieldSubtype.USER:
case FieldSubtype.USERS:
const { users } = await cache.user.getUsers(ids)
if (!users.length) {
return undefined
}
return users.map(u => ({
_id: u._id,
primaryDisplay: u.email,
email: u.email,
firstName: u.firstName,
lastName: u.lastName,
}))
default:
throw utils.unreachable(subtype)
}
}