Skip to content

Commit

Permalink
chore(examples): multi-tenant compatible with postgres ID check (#9568)
Browse files Browse the repository at this point in the history
Fixes #9565 multi-tenant
compatibility with Postgres (and custom IDs)

Adds a useful `extractID` utility:
```ts
import { Config } from '@/payload-types'
import type { CollectionSlug } from 'payload'

export const extractID = <T extends Config['collections'][CollectionSlug]>(
  objectOrID: T | T['id'],
): T['id'] => {
  if (objectOrID && typeof objectOrID === 'object') return objectOrID.id

  return objectOrID
}
```
  • Loading branch information
r1tsuu authored Nov 27, 2024
1 parent 519bb79 commit 4a854f8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
10 changes: 10 additions & 0 deletions examples/multi-tenant/src/utilities/extractID.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Config } from '@/payload-types'
import type { CollectionSlug } from 'payload'

export const extractID = <T extends Config['collections'][CollectionSlug]>(
objectOrID: T | T['id'],
): T['id'] => {
if (objectOrID && typeof objectOrID === 'object') return objectOrID.id

return objectOrID
}
15 changes: 8 additions & 7 deletions examples/multi-tenant/src/utilities/getTenantAccessIDs.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import type { User } from '../payload-types'
import type { Tenant, User } from '../payload-types'
import { extractID } from './extractID'

export const getTenantAccessIDs = (user: null | User): string[] => {
export const getTenantAccessIDs = (user: null | User): Tenant['id'][] => {
if (!user) {
return []
}
return (
user?.tenants?.reduce((acc: string[], { tenant }) => {
user?.tenants?.reduce<Tenant['id'][]>((acc, { tenant }) => {
if (tenant) {
acc.push(typeof tenant === 'string' ? tenant : tenant.id)
acc.push(extractID(tenant))
}
return acc
}, []) || []
)
}

export const getTenantAdminTenantAccessIDs = (user: null | User): string[] => {
export const getTenantAdminTenantAccessIDs = (user: null | User): Tenant['id'][] => {
if (!user) {
return []
}

return (
user?.tenants?.reduce((acc: string[], { roles, tenant }) => {
user?.tenants?.reduce<Tenant['id'][]>((acc, { roles, tenant }) => {
if (roles.includes('tenant-admin') && tenant) {
acc.push(typeof tenant === 'string' ? tenant : tenant.id)
acc.push(extractID(tenant))
}
return acc
}, []) || []
Expand Down

0 comments on commit 4a854f8

Please sign in to comment.