Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 34 additions & 52 deletions packages/plugin-multi-tenant/src/utilities/getTenantOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,62 +25,44 @@ export const getTenantOptions = async ({
return tenantOptions
}

if (userHasAccessToAllTenants(user)) {
// If the user has access to all tenants get them from the DB
const isOrderable = payload.collections[tenantsCollectionSlug]?.config?.orderable || false
const tenants = await payload.find({
collection: tenantsCollectionSlug,
depth: 0,
limit: 0,
overrideAccess: false,
select: {
[useAsTitle]: true,
...(isOrderable && { _order: true }),
},
sort: isOrderable ? '_order' : useAsTitle,
user,
})

tenantOptions = tenants.docs.map((doc) => ({
label: String(doc[useAsTitle as 'id']), // useAsTitle is dynamic but the type thinks we are only selecting `id` | `_order`
value: doc.id as string,
}))
} else {
const tenantsToPopulate: (number | string)[] = []
const isOrderable = payload.collections[tenantsCollectionSlug]?.config?.orderable || false

// i.e. users.tenants
;((user[tenantsArrayFieldName] as { [key: string]: any }[]) || []).map((tenantRow) => {
const tenantField = tenantRow[tenantsArrayTenantFieldName] // tenants.tenant
if (typeof tenantField === 'string' || typeof tenantField === 'number') {
tenantsToPopulate.push(tenantField)
} else if (tenantField && typeof tenantField === 'object') {
tenantOptions.push({
label: String(tenantField[useAsTitle]),
value: tenantField.id,
})
}
})
const userTenantIds = !userHasAccessToAllTenants(user)
? ((user[tenantsArrayFieldName] as { [key: string]: unknown }[]) || []).map((tenantRow) => {
const tenantField = tenantRow[tenantsArrayTenantFieldName]
if (typeof tenantField === 'string' || typeof tenantField === 'number') {
return tenantField
}
if (tenantField && typeof tenantField === 'object' && 'id' in tenantField) {
return tenantField.id as number | string
}
})
: undefined

if (tenantsToPopulate.length > 0) {
const populatedTenants = await payload.find({
collection: tenantsCollectionSlug,
depth: 0,
limit: 0,
overrideAccess: false,
user,
where: {
id: {
in: tenantsToPopulate,
},
const tenants = await payload.find({
collection: tenantsCollectionSlug,
depth: 0,
limit: 0,
overrideAccess: false,
select: {
[useAsTitle]: true,
...(isOrderable && { _order: true }),
},
sort: isOrderable ? '_order' : useAsTitle,
user,
...(userTenantIds && {
where: {
id: {
in: userTenantIds,
},
})
},
}),
})

tenantOptions = populatedTenants.docs.map((doc) => ({
label: String(doc[useAsTitle]),
value: doc.id as string,
}))
}
}
tenantOptions = tenants.docs.map((doc) => ({
label: String(doc[useAsTitle as 'id']),
value: doc.id as string,
}))

return tenantOptions
}
Loading