Skip to content

Instantly share code, notes, and snippets.

@francois-roget
Last active May 25, 2021 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francois-roget/fcda496cec32d2c36ec80dc31f6ee1aa to your computer and use it in GitHub Desktop.
Save francois-roget/fcda496cec32d2c36ec80dc31f6ee1aa to your computer and use it in GitHub Desktop.
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