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

75 lines
1.7 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-28 03:20:47 +13:00
): Promise<string | null> {
2023-09-20 21:07:32 +12:00
const referenceIds: string[] = []
if (Array.isArray(value)) {
2023-09-23 03:33:13 +12:00
referenceIds.push(
...value.map(idOrDoc =>
typeof idOrDoc === "string" ? idOrDoc : idOrDoc._id
)
)
2023-09-20 21:07:32 +12:00
} else if (typeof value !== "string") {
referenceIds.push(value._id)
} else {
referenceIds.push(
...value
.split(",")
.filter(x => x)
.map((id: string) => id.trim())
)
}
2023-09-15 21:21:10 +12:00
switch (subtype) {
case FieldSubtype.USER:
2023-09-20 21:07:32 +12:00
const { notFoundIds } = await cache.user.getUsers(referenceIds)
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-28 03:20:47 +13:00
return referenceIds.join(",") || null
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)
2023-09-20 21:07:32 +12:00
if (!users.length) {
return undefined
}
2023-09-20 20:35:22 +12:00
return users.map(u => ({
_id: u._id,
primaryDisplay: u.email,
email: u.email,
firstName: u.firstName,
lastName: u.lastName,
}))
2023-09-15 23:31:22 +12:00
default:
throw utils.unreachable(subtype)
}
}