UNPKG

postchain-client

Version:

Client library for accessing a Postchain node through REST.

60 lines 2.28 kB
const shuffleArray = (array) => { const shuffledArray = [...array]; for (let i = shuffledArray.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]]; } return shuffledArray; }; export const createNodeManager = ({ nodeUrls, useStickyNode = false, unavailableDuration = 5000, }) => { const nodes = nodeUrls.map((url) => ({ url, whenAvailable: 0, isAvailable: true, })); return { nodes: nodes, stickedNode: null, getAvailableNodes() { const shuffledAvailableNodes = shuffleArray(this.nodes.filter((node) => node.isAvailable)); // set sticky node as the first node, and then shuffle the rest if (useStickyNode && this.stickedNode && this.stickedNode.isAvailable) { const nodesWithoutSticky = shuffledAvailableNodes.filter((node) => node !== this.stickedNode); return [this.stickedNode, ...nodesWithoutSticky]; } return shuffledAvailableNodes; }, setStickyNode(node) { this.stickedNode = node; }, getNode() { const nodes = this.getAvailableNodes(); if (nodes.length === 0) { return null; } const index = Math.floor(Math.random() * nodes.length); const node = nodes[index]; if (!useStickyNode) { return node; } if (!this.stickedNode) { this.setStickyNode(node); return node; } return this.stickedNode; }, makeNodeUnavailable(nodeUrl) { if (this.stickedNode && this.stickedNode.url === nodeUrl) { this.stickedNode = null; } const updatedNodes = nodes.map((node) => { if (node.url === nodeUrl) { return Object.assign(Object.assign({}, node), { isAvailable: false, whenAvailable: Date.now() + unavailableDuration }); } return node; }); this.nodes = updatedNodes; }, }; }; //# sourceMappingURL=nodeManager.js.map