Skip to main content

fuse-datastore-client

Table of Contents

This repository hosts the datastore-client library of fuse

The library is useful to invoke datastore operations to create/read/update/delete/query Items from the datastore

Installation

npm install @appfire/fuse-datastore-client

Features

  • the client library is useful to make operations on datastore, which is data residency enabled
  • Allows basic operations like
    • Create Item
    • Update Item
    • Delete Item
    • List Items by filter
    • Query by Index ( using GSI, i.e global secondary Index)

Usage

Importing the fuse-datastore-client FuseDsSDK

import { FuseDsSDK } from "@appfire/fuse-datastore-client";

creating and instance of FuseDsSDK, in both browser and NodeJS environments

Browser

const fuseDsSDK = new FuseDsSDK({
appKey: "org.swift.confluence.refapp",
productType: "Confluence",
});

NodeJS

Environment

  • API_PATH: the fuse services URL, the value will be
    • DTS: <compute region>.dts-common.appfire.app
    • PROD: <compute region>.common.appfire.app
  • COMPUTE_PREFIX represents the compute region to which the API call needs to be made
    • example us/de/au
const fuseDsSDK = new FuseDsSDK({
appKey: "org.swift.confluence.refapp",
productType: "Confluence",
});

fuseDsSDK.withTokenFn(tokenFn);

Props: configuring the FuseDsSDK

  • appKey: Indicates the application key, example org.swift.confluence.refapp
  • tokenFn: the function which can return the product's token, only needed when the FuseDsSDK is used in node environment where the product context is not available to build a token
  • cacheDuration: duration for which the token should be cached
  • productType: Confluence/Jira/Monday
  • domain: need to be specified only when used at the backend Lambda

Example

Token Function tokenFn, when used in NodeJS context

import { APIGatewayProxyEvent } from "aws-lambda";

const tokenFunction = (event: APIGatewayProxyEvent) => {
const authorizationHeader =
event.headers["Authorization"] || event.headers["Authorization"];
if (authorizationHeader === undefined) {
throw new Error("Authorization header is missing"); // Or provide a default value
}
return authorizationHeader;
};

// builds function with pre-bind token
export const buildTokenFn = (event: APIGatewayProxyEvent) => {
return () => tokenFunction(event);
};

Set Item: used to create/update an Item.

fuseDsSDK.setItem(
"APP",
"org.swift.confluence.refapp",
JSON.stringify({
defaultObj,
})
);

Get Item: used to retrieve an Item.

const response = fuseDsSDK.getItem("PROFILE", "p1", ["defaultObj"]);

//the response is a JSON string which is available
response.data.getItemProperties;

Get Items: used to retrieve list of items

props

  • entity: the type of entity example APP/PROFILE/CUSTOM etc
  • entity_id: uniquely identifies the entity
  • propKeys: the array of properties to retrieve from the datastore item,
  • filters: stringified version of array of filter
const filters = JSON.stringify([  key: 'name',
condition: ConditionType.BeginsWith,
value: 'tar',
}])

const response: any = await fuseDsSDK.getItems(entity, entity_id, propKeys, filters);

const data = JSON.parse(response.data.getItems);

Delete Item : used to delete an Item matching the entity_id

props

  • entity: the type of entity example APP/PROFILE/CUSTOM etc
  • entity_id: uniquely identifies the entity
fuseDsSDK.setNestedItemProperty(
entity, // APP
entity_id // unique entity Id with in the entries for entity APP
);

Delete Item Property: used to delete properties of an item.

props

  • entity: the type of entity example APP/PROFILE/CUSTOM etc
  • entity_id: uniquely identifies the entity
fuseDsSDK.deleteItemProperties("PROFILE", "demoGitHubProfile", [
"repositoryName",
"repositoryAdmin",
]);

Set Nested Item Property: used to set a nested Item property

props

  • entity: the type of entity example APP/PROFILE/CUSTOM etc
  • entity_id: uniquely identifies the entity
  • propKeys: the array of properties to retrieve from the datastore item,
  • filters: stringified version of array of filter
fuseDsSDK.setNestedItemProperty(
entity, // APP
entity_id, // unique entity Id with in the entries for entity APP
"defaultObj", // nested item property key
JSON.stringify({
address: { city: "Bengaluru", pin: 2222, newProp: true },
})
);

Features

  • Get a multi-tenant safe instance of DynamoDB
  • Cache the recently used connection
  • Client code to connect to datastore

Installing

Using npm:

$ npm install @appfire/fuse-datastore

Once the package is installed, you can import the library using import:

import {
FuseDynamoDBClientFactory,
FuseDynamoInstance,
} from '@appfire/fuse-datastore';

Example

Get Instance of DynamoDB Client

The API will return an instance of DynamoDB Client which safe for multiple tenants. You will need to provide tenantId in the constructor. Library will make sure that Lambda only have access to the records of specified tenant. It will also have improved performance by caching the connection. Note access of the instance expires in 15 minutes. If you need cache optimised version then use below example.

const ddFactory = FuseDynamoInstance.getInstance();
const ddb = await ddFactory.getClient(tenantId);

You can directly use ddb (DynamoDB client AWS SDK v3)

Get Instance of DynamoDB Client Cache Optimised

The API will return an instance of DynamoDB Client which safe for multiple tenants. You will need to provide tenantId in the constructor. Library will make sure that Lambda only have access to the records of specified teant. It will also have improved performance by caching the connection. The connection is created for 15 minutes. The cache optimised version will automatically request a new instance when cache expires.

const ddFactory = FuseDynamoInstance.getInstanceCacheOptimised();
const ddb = await ddFactory.getClient(tenantId);

You can directly use ddb (DynamoDB client AWS SDK v3)

Work with Dynamoose

Dynamoose is a popular ORM library for DynamoDB. You can read more about it here. (https://dynamoosejs.com/getting_started/Introduction) You can use above ddb object to set as the interaction layer for dynamodb in Dynamoose

dynamoose.aws.ddb.set(ddb);

getItem Method

The getItem method is designed to asynchronously retrieve specific properties of an entity from a GraphQL endpoint. This method is typically used to fetch detailed information about a specific entity by providing its unique identifier and specifying the properties of interest.

Method Signature

async getItem(
entity: string,
entity_id: string,
prop_keys: string[]
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entity you want to retrieve information about.
  • entity_id (string): The unique identifier of the specific entity you want to fetch details for.
  • prop_keys (array of strings): An array of property keys representing the specific properties of the entity you want to retrieve.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async getItem(
entity: string,
entity_id: string,
prop_keys: string[]
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: getItemProperties,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
prop_keys,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (getItemProperties). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entity.
    • entity_id: The unique identifier of the specific entity.
    • prop_keys: An array of property keys specifying the properties to retrieve.

Important Notes

  • Ensure that the GraphQL query (getItemProperties) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, property1, property2) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

getItems Method

The getItems method is designed to asynchronously retrieve a list of entities from a GraphQL endpoint based on specified filters, property keys, and, optionally, an entity ID. This method is useful for querying multiple entities based on specific criteria.

Method Signature

async getItems(
entity: string,
entity_id: string | undefined,
propKeys: string[],
filters: string
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entities you want to retrieve.
  • entity_id (string | undefined): The unique identifier of the specific entity you want to fetch details for. It can be undefined if not applicable.
  • propKeys (array of strings): An array of property keys representing the specific properties of the entities you want to retrieve.
  • filters (string): A JSON string representing filters for querying entities. The filters define conditions that entities must meet to be included in the result.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async getItems(
entity: string,
entity_id: string | undefined,
propKeys: string[],
filters: string
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
const variables = entity_id
? {
appkey: this.dsConfig.appKey,
entity,
entity_id,
propKeys,
filters,
}
: { appkey: this.dsConfig.appKey, entity, propKeys, filters };
return await API.graphql({
query: getItems,
authToken,
variables,
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (getItems). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entities.
    • entity_id: The unique identifier of the specific entity (optional and can be undefined).
    • propKeys: An array of property keys specifying the properties to retrieve.
    • filters: A JSON string representing filters for querying entities.

Important Notes

  • Ensure that the GraphQL query (getItems) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, property1, property2, {"key": "value"}) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

setItem Method

The setItem method is designed to asynchronously update the properties of a specific entity on a GraphQL endpoint. This method is useful for modifying the properties of an entity by providing its unique identifier, the properties to update, and an optional permission template.

Method Signature

async setItem(
entity: string,
entity_id: string,
props: string,
permissionTemplate: PermissionTemplate = PermissionTemplate.WRITE_ADMIN_READ_ALL
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entity you want to update.
  • entity_id (string): The unique identifier of the specific entity you want to update.
  • props (string): A JSON string representing the properties and their new values that you want to update for the entity.
  • permissionTemplate (PermissionTemplate, optional): An optional parameter specifying the permission template for the entity. It is set to PermissionTemplate.WRITE_ADMIN_READ_ALL by default.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async setItem(
entity: string,
entity_id: string,
props: string,
permissionTemplate: PermissionTemplate = PermissionTemplate.WRITE_ADMIN_READ_ALL
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: setItemProperties,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
props,
permissionTemplate,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (setItemProperties). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entity.
    • entity_id: The unique identifier of the specific entity.
    • props: A JSON string representing the properties and their new values that you want to update for the entity.
    • permissionTemplate: The permission template for the entity, defaulting to PermissionTemplate.WRITE_ADMIN_READ_ALL.

Important Notes

  • Ensure that the GraphQL query (setItemProperties) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, {"propertyToUpdate": "newValue"}) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

setNestedItemProperty Method

The setNestedItemProperty method is designed to asynchronously update a nested property of a specific entity on a GraphQL endpoint. This method is useful for modifying a nested property of an entity by providing its unique identifier, the key of the nested property, and the new value for that nested property.

Method Signature

async setNestedItemProperty(
entity: string,
entity_id: string,
propKey: string,
propVal: string
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entity you want to update.
  • entity_id (string): The unique identifier of the specific entity you want to update.
  • propKey (string): The key of the nested property you want to update.
  • propVal (string): A JSON string representing the new value for the nested property.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async setNestedItemProperty(
entity: string,
entity_id: string,
propKey: string,
propVal: string
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: setNestedItemProperty,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
propKey,
propVal,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (setNestedItemProperty). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entity.
    • entity_id: The unique identifier of the specific entity.
    • propKey: The key of the nested property to update.
    • propVal: A JSON string representing the new value for the nested property.

Important Notes

  • Ensure that the GraphQL query (setNestedItemProperty) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, nestedProperty, {"nestedKey": "nestedValue"}) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

getItemsWithGSI Method

The getItemsWithGSI method is designed to asynchronously retrieve a list of entities using a Global Secondary Index (GSI) from a GraphQL endpoint. This method allows you to query entities based on specific criteria, utilizing a GSI to enhance query performance.

Method Signature

async getItemsWithGSI(
entity: string,
entity_id: string,
gsi: string,
gsiPk: string,
propKeys: string[],
filters: string
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entities you want to retrieve.
  • entity_id (string): The unique identifier of the specific entity you want to fetch details for.
  • gsi (string): The name of the Global Secondary Index (GSI) to use for querying entities.
  • gsiPk (string): The partition key for the GSI.
  • propKeys (array of strings): An array of property keys representing the specific properties of the entities you want to retrieve.
  • filters (string): A JSON string representing filters for querying entities. The filters define conditions that entities must meet to be included in the result.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async getItemsWithGSI(
entity: string,
entity_id: string,
gsi: string,
gsiPk: string,
propKeys: string[],
filters: string
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: getItemsWithGSI,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
gsi,
gsiPk,
filters,
propKeys,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (getItemsWithGSI). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entities.
    • entity_id: The unique identifier of the specific entity.
    • gsi: The name of the Global Secondary Index (GSI) to use for querying entities.
    • gsiPk: The partition key for the GSI.
    • filters: A JSON string representing filters for querying entities.
    • propKeys: An array of property keys specifying the properties to retrieve.

Important Notes

  • Ensure that the GraphQL query (getItemsWithGSI) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, yourGSIName, gsiPartitionKey, property1, property2, {"key": "value"}) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

bulkUpdate Method

The bulkUpdate method is designed to asynchronously update multiple entities based on specified filters and update properties on a GraphQL endpoint. This method is useful for performing bulk updates to entities that meet specific criteria.

Method Signature

async bulkUpdate(
entity: string,
entity_id: string,
filters: string,
updateProps: string
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entities you want to update.
  • entity_id (string): The unique identifier of the specific entity you want to fetch details for.
  • filters (string): A JSON string representing filters for querying entities. The filters define conditions that entities must meet to be included in the bulk update.
  • updateProps (string): A JSON string representing the properties and their new values that you want to update for the entities that match the specified filters.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async bulkUpdate(
entity: string,
entity_id: string,
filters: string,
updateProps: string
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: bulkUpdate,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
filters,
updateProps,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (bulkUpdate). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entities.
    • entity_id: The unique identifier of the specific entity.
    • filters: A JSON string representing filters for querying entities.
    • updateProps: A JSON string representing the properties and their new values that you want to update for the entities.

Important Notes

  • Ensure that the GraphQL query (bulkUpdate) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, {"key": "value"}, {"propertyToUpdate": "newValue"}) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

deleteItemProperties Method

The deleteItemProperties method is designed to asynchronously delete specific properties of a specific entity on a GraphQL endpoint. This method allows you to remove specific properties from an entity by providing its unique identifier and specifying the properties to delete.

Method Signature

async deleteItemProperties(
entity: string,
entity_id: string,
prop_keys: string[]
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entity from which to delete properties.
  • entity_id (string): The unique identifier of the specific entity from which to delete properties.
  • prop_keys (array of strings): An array of property keys representing the specific properties to delete from the entity.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async deleteItemProperties(
entity: string,
entity_id: string,
prop_keys: string[]
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: deleteItemProperties,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
prop_keys,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (deleteItemProperties). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entity from which to delete properties.
    • entity_id: The unique identifier of the specific entity from which to delete properties.
    • prop_keys: An array of property keys specifying the properties to delete.

Important Notes

  • Ensure that the GraphQL query (deleteItemProperties) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID, property1, property2) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

deleteItem Method

The deleteItem method is designed to asynchronously delete a specific entity on a GraphQL endpoint. This method allows you to remove an entity by providing its unique identifier.

Method Signature

async deleteItem(
entity: string,
entity_id: string
): Promise<GraphQLResult<any>>;

Parameters

  • entity (string): The type or category of the entity to delete.
  • entity_id (string): The unique identifier of the specific entity to delete.

Return Value

The method returns a Promise that resolves to a GraphQLResult<any>. The GraphQLResult is a generic type that encapsulates the result of a GraphQL operation.

Usage

Example

async deleteItem(
entity: string,
entity_id: string
): Promise<GraphQLResult<any>> {
const authToken: string = await this.getAuthToken();
return API.graphql({
query: deleteItem,
authToken,
variables: {
appkey: this.dsConfig.appKey,
entity,
entity_id,
},
});
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the getAuthToken method. This token is required to authenticate the GraphQL operation.

  2. GraphQL Query Execution: The method uses the Amplify API.graphql function to execute a GraphQL query (deleteItem). The query is passed along with the authentication token and the specified variables.

  3. Variables:

    • appkey: The application key configured in dsConfig.appKey.
    • entity: The type or category of the entity to delete.
    • entity_id: The unique identifier of the specific entity to delete.

Important Notes

  • Ensure that the GraphQL query (deleteItem) is correctly imported from the appropriate file in your project.
  • Replace placeholder values (yourEntityType, uniqueEntityID) with actual values relevant to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL operation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

bulkUpdateSub Method

The bulkUpdateSub method is designed to asynchronously subscribe to a GraphQL subscription for bulk updates on a GraphQL endpoint. This method enables you to receive real-time updates when bulk updates occur, and it includes handlers for successful data reception, errors, and optional completion.

Method Signature

async bulkUpdateSub(
onSubscribeHandler: (data: any) => void,
onError: (error: any) => void,
onComplete?: () => void
): Promise<void>;

Parameters

  • onSubscribeHandler ((data: any) => void): A callback function that handles incoming data when a new bulk update event occurs. The data parameter contains the received information.
  • onError ((error: any) => void): A callback function that handles errors that may occur during the subscription. The error parameter contains details about the error.
  • onComplete (() => void, optional): An optional callback function that handles the completion of the subscription.

Return Value

The method returns a Promise<void> to indicate that the subscription has been initiated.

Usage

Example

async bulkUpdateSub(
onSubscribeHandler: (data: any) => void,
onError: (error: any) => void,
onComplete?: () => void
): Promise<void> {
const authToken: string = await CacheService.getData<string>(
this.cacheKey,
this.dsConfig.cacheDuration ?? 10,
this.dsConfig.tokenFn ?? (() => AP.context.getToken())
);
API.graphql<GraphQLSubscription<OnBulkUpdateSubscription>>(
graphqlOperation(bulkUpdateSubscription, {}, authToken)
).subscribe(
(data: { value: unknown }) => onSubscribeHandler(data.value),
onError,
onComplete
);
}

How it Works

  1. Get Authentication Token: The method first obtains an authentication token using the CacheService.getData method. This token is required to authenticate the GraphQL subscription.

  2. GraphQL Subscription Execution: The method uses the Amplify API.graphql function to initiate a GraphQL subscription (bulkUpdateSubscription). The subscription is configured with the provided authentication token.

  3. Subscription Handlers:

    • onSubscribeHandler: This function is called when a new bulk update event occurs. It receives the data parameter containing the received information, allowing you to handle and process the data as needed.
    • onError: This function is called if an error occurs during the subscription. It receives the error parameter containing details about the error, enabling you to handle errors appropriately.
    • onComplete (optional): This function is called when the subscription is completed. It is optional and can be used to handle the completion event.

Important Notes

  • Ensure that the GraphQL subscription (bulkUpdateSubscription) is correctly imported from the appropriate file in your project.
  • Replace placeholder values and logic in the example with actual values and handling specific to your application.

Error Handling

The method is asynchronous, and errors can occur during the GraphQL subscription initiation. Be sure to handle potential errors using try-catch blocks or any error-handling mechanism suitable for your application.

try {
// ... (method invocation)
} catch (error) {
console.error('Error:', error);
}

Adjust the error-handling strategy based on your application's requirements and standards.

Contribution guidelines

  • Writing tests
  • Based on type of changes (Major, Minor, and Patch) use changeset to update package versions. for more information please check here

Who do I talk to?