Last active
May 25, 2021 06:31
-
-
Save francois-roget/fcda496cec32d2c36ec80dc31f6ee1aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import {Permission} from "../Types"; | |
import PermissionContext from "./PermissionContext"; | |
type Props = { | |
fetchPermission: (p: Permission) => Promise<boolean> | |
} | |
type PermissionCache = { | |
[key:string]: boolean; | |
} | |
// This provider is intended to be surrounding the whole application. | |
// It should receive a method to fetch permissions as parameter | |
const PermissionProvider: React.FunctionComponent<Props> = ({fetchPermission, children}) => { | |
const cache: PermissionCache = {}; | |
// Creates a method that returns whether the requested permission is granted to the current user | |
const isAllowedTo = async (permission: Permission): Promise<boolean> => { | |
if(Object.keys(cache).includes(permission)){ | |
return cache[permission]; | |
} | |
const isAllowed = await fetchPermission(permission); | |
cache[permission] = isAllowed; | |
return isAllowed; | |
}; | |
// This component will render its children wrapped around a PermissionContext's provider whose | |
// value is set to the method defined above | |
return <PermissionContext.Provider value={{isAllowedTo}}>{children}</PermissionContext.Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment