@fnet/inter-service-js
v0.9.10
Published
## Introduction
Downloads
138
Readme
@fnet/inter-service-js
Introduction
@fnet/inter-service-js is a JavaScript library designed to facilitate communication between different services or components running in separate browser windows or frames. This project aims to simplify the integration of web applications that need to exchange messages or invoke functionalities from each other, efficiently creating a network of interconnected services within a browser environment.
How It Works
The library functions by establishing communication channels between services using the browser's messaging capabilities such as the postMessage
API and MessageChannel
. By associating unique identifiers with each service, it ensures that messages are accurately routed to their intended destination. It includes mechanisms to find available routes for communication dynamically, ensuring robust and reliable message exchanges even in complex multi-window setups.
Key Features
- Service Connection: Establishes connections to external services using unique service IDs, ensuring reliable routing of messages.
- Message Routing: Supports finding routers capable of directing communication to appropriate services or frames.
- Handler Registration: Allows services to register handlers for specific methods, enabling customized functionality exchange.
- Proxy Communication: Facilitates invoking methods on a service from another service without direct dependence.
- Event Handling: Built-in event emitter for managing event-driven interactions between services.
- Safety Checks: Includes checks to prevent self-connection and other potential misconfigurations.
Conclusion
@fnet/inter-service-js is valuable for developers looking to create interconnected web applications where components need to communicate efficiently across different environments. By abstracting and simplifying the communication process, it helps developers focus on building feature-rich applications without worrying about the intricacies of cross-window messaging.
Developer Guide for @fnet/inter-service-js
Overview
The @fnet/inter-service-js
library provides a communication framework for connecting services running in different window contexts or frames. It facilitates message-passing between these services using the postMessage
API, making it easier to build applications with multiple services communicating in a loosely-coupled manner. The library includes functionality for connecting services, proxying methods across services, and managing communication channels securely and efficiently.
Installation
To install this library, use npm or yarn. Simply run:
npm install @fnet/inter-service-js
or
yarn add @fnet/inter-service-js
Usage
To get started with @fnet/inter-service-js
, you need to initialize the library and create communication channels between services.
import interServiceJs from '@fnet/inter-service-js';
async function setupService() {
const service = await interServiceJs({
id: 'my-service-id',
verbose: true,
router: true,
});
// Example: Register a method that echoes the received message
service.register({
method: 'echo',
handler: (args) => {
console.log('Echo received:', args);
return args;
}
});
// Example: Connect to another service
try {
const result = await service.connect({
window: otherWindow,
serviceId: 'other-service-id'
});
console.log('Connected to service:', result);
} catch (error) {
console.error('Connection failed:', error.message);
}
}
setupService();
Examples
Registering a Service Method
You can register methods that other services can call. For instance, to register a greet
method:
service.register({
method: 'greet',
handler: (args) => {
return `Hello, ${args.name}`;
}
});
Proxying a Method Call to Another Service
If you need to call a method on another service:
service.proxy({
method: 'getTime',
service: 'time-service-id',
args: { timezone: 'UTC' }
}).then(response => {
console.log('Current time in UTC:', response);
}).catch(error => {
console.error('Failed to get time:', error.message);
});
Finding and Connecting to a Router
Before connecting to a service, a router needs to be identified:
service.findRouter({
timeout: 2000,
where: { serviceId: 'target-service-id' }
}).then(router => {
if (router) {
console.log('Router found:', router);
} else {
console.log('No router found within the timeout period.');
}
});
Unregistering a Service Method
To unregister a previously registered method:
service.unregister({ method: 'greet' });
Acknowledgement
The development of @fnet/inter-service-js
leverages the nanoid
library for generating unique identifiers and the eventemitter3
for event handling. Special thanks to the developers and contributors of these libraries for providing essential functionality that enhances our library's capabilities.
Input Schema
$schema: https://json-schema.org/draft/2020-12/schema
type: object
properties:
id:
type: string
pattern: ^([a-z\-_]+)$
description: The unique service ID. Should be lowercase and may include '-' and '_'
verbose:
type: boolean
description: Enable verbose output for debugging
router:
type: boolean
description: Indicate if the service can act as a router
required:
- id