Using Access function with custom User interface

default discord avatar
Martin Törnros
3 months ago
1

When using Access Controls I can for example create a function

isSuperAdmin

to only let users with a certain role create new content, like.



const isSuperAdmin: Access<any, User> = ({req: {user}}) => {
  return (user?.role?.value as Role).hierarchy <= 1
}

and


access: {
    create: isSuperAdmin,
    ...

and within the function,

user

would be recognised and typed as a

User

.



How could I achieve the same without having to create a separate function? The following code works but in the editor the

user

variable is typed as

any

(not

User

) hence not recognising the

role

field:


create: ({req: {user}}) => {
      return (user?.role?.value as Role).hierarchy <= 1
    }

I realise I'd probably have to specify

Access<any, User>

(or, at least

User

somewhere) but I can't figure out where.



(I'm aware that creating a function is good for reusability, but the admin case is just an example. Please ignore the reusability aspect when answering the question)



Thanks!



Solution:


create: ({req: {user}}) => {
  return ((user as User)?.role?.value as Role).hierarchy <= 1
}
    Open the post
    Continue the discussion in Discord
    Like what we're doing?
    Star us on GitHub!

    Star

    Connect with the Payload Community on Discord

    Discord

    online

    Can't find what you're looking for?

    Get help straight from the Payload team with an Enterprise License.