Create relations

Once you've created your relation definitions, you can start creating relations between resources and targets. Then, you can finally add the access control checks to your application. We'll start with looking at the relevant objects used in creation and checking of relations.

Understanding the Data Types

When creating a relation, we have the FGARelation type which defines a relation between a resource and a target.

type FGARelation = {
  resource: string;
  resourceType?: string;
  relation: string;
  target: string;
  targetType?: string;
};

When checking to see if a relation exists, one of the options involves the AuthzRelationQuery type which is used to query the service to see if a given relation exists. The function that takes this object in will return it with the hasRelation boolean field set to true or false depending on whether the relation exists or not.

Other functions include the ability to check what relations exist for a given resource or target.

CheckResponseRelation = {
  allowed: boolean;
  tuple: FGARelation;
};

Creating, Updating, and Deleting Relations

Install SDK

Terminal
npm i --save @descope/node-sdk

Import and initialize Management SDK

import DescopeClient from '@descope/node-sdk';
 
const managementKey = "xxxx"
 
try{
    //  baseUrl="<URL>" // When initializing the Descope clientyou can also configure the baseUrl ex: https://auth.company.com  - this is useful when you utilize CNAME within your Descope project.
    const descopeClient = DescopeClient({ projectId: '__ProjectID__', managementKey: managementKey });
} catch (error) {
    // handle the error
    console.log("failed to initialize: " + error)
}
 
// Note that you can handle async operation failures and capture specific errors to customize errors.
//     An example can be found here: https://github.com/descope/node-sdk?tab=readme-ov-file#error-handling

Create given relations

The createRelations function creates a given array of relations.

const relations: FGARelation[] = [
  {
    resource: 'some-doc',
    resourceType: 'doc',
    relation: 'owner',
    target: 'u1',
    targetType: 'user',
  },
];
 
await descopeClient.management.fga.createRelations(relations);

Delete given relations

The deleteRelations function deletes a given array of relations.

const relations: FGARelation = [{
    resource: 'some-doc',
    resourceType: 'doc',
    relation: 'owner',
    target: 'u1',
    targetType: 'user',
  },];
 
await sdk.management.fga.deleteRelations(relations)

Delete all relations for given resources

The deleteRelationsForResources function takes an array of resources and deletes all relations for those resources.

const resources: string[] = [];
 
await descopeClient.management.authz.deleteRelationsForResources(resources);

Next

We'll move on to checking relations.

Was this helpful?

On this page