Tutorial: IPC with ReactJS and Nitrogen

IPC with ReactJS and Nitrogen

IPC

IPC Client

NPM Setup

To integrate the IPC library into your project, follow these steps to install the npm module:

npm install --save @n7-io/ipc

IPC Setup

For IPC setup, create a configuration object with the necessary details, including domains, account ID, and the default category to preload. To obtain your account ID, please submit a support ticket to care@nviz.com.

const IPC_CONFIG = {
    domain: "api.ncc.n7.io",
    accountId: "XXXXXX",
    ctCatsToPreload: ["xxxxxxxx"],
};

Example

Initialize the IPC query manager with the provided configuration:

import { init } from "@n7-io/ipc";
const queryManager = init(IPC_CONFIG);

// Define default settings and parameters
const defaultLimit = 5;
const defaultQueryParams = {
    filters: [],
    sort: { attributeId: null, order: 0 },
    pagination: { offset: 0, limit: defaultLimit },
};

// Define specific query parameters
const selectedQueryParams = {
    filters: [271, 7, 1789, 2288],
    sort: { attributeId: 35312, order: 0 },
    pagination: { offset: 0, limit: defaultLimit },
};
// Define default sort options and results
const defaultSortOptions = [{ attributeId: null, label: "Relevance", order: 0, value: "0.null" }];
const defaultResults = { categories: [], brands: [], products: [] };

Product Details Service

To retrieve product details based on a product ID, follow these steps using the IPC library:

Feel free to customize the logic within the setProductsData functions according to your application's requirements.

// Get product details by product ID

// Define a function to handle the product data
const setProductsData = (value) => {
    // Implement logic for rendering product details
}

// Specify the product ID
const productId = Number(1010);
// Check if the provided ID is valid
if (Number.isNaN(productId)) return;

// Create a product details service using the query manager
const detailService = queryManager.details(productId);
// Subscribe to the product details and update the UI
const detailSubscription = detailService.out.subscribe((data) => {
    setProductsData(data.results);
});
// Trigger the service to fetch data
detailService.next();

// Unsubscribe from the service and clean up resources when done
detailSubscription.unsubscribe();
detailService.destroy();


Product List Service

To fetch all products based on a category ID, use the IPC library as demonstrated below:

Feel free to customize the logic within the setProductListData functions according to your application's requirements.

// Get all products by category ID

// Specify the category ID
const ipcCategoryId = 'xxxxxxxx'
// Define a function to handle the product list data
const setProductListData = (value) => {
    // Implement logic for listing products
}
// Create a product list service using the query manager
const productService = queryManager.products(ipcCategoryId);
// Subscribe to the product list and update the UI
const productSubscription = productService.products.subscribe(({ results, timeTaken }) => {
    setProductListData(results);
});
// Trigger the service to fetch data
productService.next(productQueryParams);

// Unsubscribe from the service and clean up resources when done
productSubscription.unsubscribe();
productService.destroy();

Product Search Service

To implement a product search service using the IPC library, follow these steps:

Adjust the logic within the setResults function to suit your application's requirements for displaying search results.



// Define a function to handle the search results
const setResults = (value) => {
    // Implement logic for listing search results
}

// Create a product search service using the query manager
const searchService = queryManager.search();

// Subscribe to the search results and update the UI
const searchSubscription = searchService.out.subscribe(({ results, timeTaken }) => {
    setResults(results)
});

// Specify the search term
let searchTerm = "Red Shirt";
// Check if the search term is valid
if (searchTerm && searchTerm.trim().length > 0) {
    searchService.next(searchTerm);
} else {
    // Ignore the next search event and provide fallback results for an invalid search term
    searchService.ignoreNext();
    setResults(defaultResults); // Fallback result if the search term is invalid
}

// Unsubscribe from the service and clean up resources when done
searchSubscription.unsubscribe();
searchService.destroy();

Product Filter Service

Customize the logic within the getName, setSortOptions, and setFilterFacets functions according to your application's needs.

// Get all filterable options

// Define a function for formatting filter keys
const getName = (value) => {
    // Implement logic for formatting filter keys
}

// Define functions for updating sort options and rendering filter options
const setSortOptions = (value) => {
    // Implement logic for updating sort options available
}

const setFilterFacets = (value) => {
    // Implement logic for rendering filter options
}

const ipcCategoryId = 'xxxxxxxx'
// Create a product filter service using the query manager and specify the category ID
const filterService = queryManager.filters(ipcCategoryId);

// Subscribe to the filter results and update the UI
const filterSubscription = filterService.out.subscribe(({ results }) => {
    // Update filter facets based on the received results
    setFilterFacets(results.filters);

    // Generate supported sort options based on filter results
    const supportedSortOptions = results.sorts
        .map((item) => {
            return [
                {
                    attributeId: item.attributeId,
                    label: `${getName(item.label)} - ${item.attributeType === "number" ? "Low to High" : "A to Z"}`,
                    order: 0,
                    value: `0.${item.attributeId}`,
                },
                {
                    attributeId: item.attributeId,
                    label: `${getName(item.label)} - ${item.attributeType === "number" ? "High to Low" : "Z to A"}`,
                    order: 1,
                    value: `1.${item.attributeId}`,
                },
            ];
        })
        .flat();

    // Update sort options with default and supported options
    setSortOptions([...defaultSortOptions, ...supportedSortOptions]);
});
// Trigger the filter service to fetch data
filterService.next();

// Unsubscribe from the service and clean up resources when done
filterSubscription.unsubscribe();
filterService.destroy();

IPC Api

Add Product to IPC

To add a product to IPC, sample JSON request body (product.json):

{
  "accountId": "XXXXXX",
  "items": [
    {
      "id": "12312",
      "version": 1,
      "name": "Red Shirt",
      "attributes": [
        {
          "key": "images",
          "value": [
            "https://www.example.com/images/product/xxxxxxxx/default.jpg",
          ],
          "string": "string"
        },
        {
          "key": "brand",
          "value": [
            "BrandName"
          ],
          "string": "string"
        },
        {
          "key": "price",
          "value": [
            "1000.00"
          ],
          "string": "number"
        }
      ],
      "categories": [
        {
          "id": "xxxxxxxx",
          "name": "Clothing"
        }
      ]
    }
  ]
}

Example curl command to make API request:

curl -d "@product.json" -H 'Authorization: <IPCToken>' -H 'Content-Type: application/json' -X POST 'https://api.ncc.n7.io/v1/nitro/ncc/sync/items/add'

Ensure to replace <IPCToken> with the actual IPC token for authorization.

This API endpoint allows you to synchronize product data with IPC. Customize the product.json file with the specific details of the product you intend to add.

Publish changes to IPC

To publish changes to IPC, you can use the following curl command:

curl -d '{"accountId":"XXXXXX"}' -H 'Authorization: <IPCToken>' -H 'Content-Type: application/json' -X POST 'https://api.ncc.n7.io/v1/nitro/ncc/sync/publish'

Make sure to replace <IPCToken> with the actual IPC token for authorization.

This API endpoint enables you to publish any changes made to the synchronized data with IPC. The provided JSON payload specifies the account ID for which the changes should be published.

Use this command when you need to ensure that the latest updates are reflected in IPC. Adjust the accountId in the payload to match the specific account for which you want to publish changes.