Latest Threat Research:SANDWORM_MODE: Shai-Hulud-Style npm Worm Hijacks CI Workflows and Poisons AI Toolchains.Details
Socket
Book a DemoInstallSign in
Socket

qified

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

qified - npm Package Compare versions

Comparing version
0.4.3
to
0.5.0
+1
-146
dist/index.cjs

@@ -1,146 +0,1 @@

"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
MemoryMessageProvider: () => MemoryMessageProvider,
Qified: () => Qified
});
module.exports = __toCommonJS(index_exports);
// src/memory/message.ts
var MemoryMessageProvider = class {
_subscriptions;
constructor() {
this._subscriptions = /* @__PURE__ */ new Map();
}
get subscriptions() {
return this._subscriptions;
}
set subscriptions(value) {
this._subscriptions = value;
}
async publish(topic, message) {
const subscriptions = this._subscriptions.get(topic) ?? [];
for (const subscription of subscriptions) {
await subscription.handler(message);
}
}
async subscribe(topic, handler) {
if (!this._subscriptions.has(topic)) {
this._subscriptions.set(topic, []);
}
this._subscriptions.get(topic)?.push(handler);
}
async unsubscribe(topic, id) {
if (id) {
const subscriptions = this._subscriptions.get(topic);
if (subscriptions) {
this._subscriptions.set(
topic,
subscriptions.filter((sub) => sub.id !== id)
);
}
} else {
this._subscriptions.delete(topic);
}
}
async disconnect() {
this._subscriptions.clear();
}
};
// src/index.ts
var Qified = class {
_messageProviders = [];
/**
* Creates an instance of Qified.
* @param {QifiedOptions} options - Optional configuration for Qified.
*/
constructor(options) {
if (options?.messageProviders) {
this._messageProviders = options.messageProviders;
}
}
/**
* Gets or sets the message providers.
* @returns {MessageProvider[]} The array of message providers.
*/
get messageProviders() {
return this._messageProviders;
}
/**
* Sets the message providers.
* @param {MessageProvider[]} providers - The array of message providers to set.
*/
set messageProviders(providers) {
this._messageProviders = providers;
}
/**
* Subscribes to a topic. If you have multiple message providers, it will subscribe to the topic on all of them.
* @param {string} topic - The topic to subscribe to.
* @param {TopicHandler} handler - The handler to call when a message is published to the topic.
*/
async subscribe(topic, handler) {
const promises = this._messageProviders.map(
async (provider) => provider.subscribe(topic, handler)
);
await Promise.all(promises);
}
/**
* Publishes a message to a topic. If you have multiple message providers, it will publish the message to all of them.
* @param {string} topic - The topic to publish to.
* @param {Message} message - The message to publish.
*/
async publish(topic, message) {
const promises = this._messageProviders.map(
async (provider) => provider.publish(topic, message)
);
await Promise.all(promises);
}
/**
* Unsubscribes from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the topic.
* @param topic - The topic to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the topic will be unsubscribed.
*/
async unsubscribe(topic, id) {
const promises = this._messageProviders.map(
async (provider) => provider.unsubscribe(topic, id)
);
await Promise.all(promises);
}
/**
* Disconnects from all providers.
* This method will call the `disconnect` method on each message provider.
*/
async disconnect() {
const promises = this._messageProviders.map(
async (provider) => provider.disconnect()
);
await Promise.all(promises);
this._messageProviders = [];
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MemoryMessageProvider,
Qified
});
"use strict";var c=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var h=(t,s)=>{for(var i in s)c(t,i,{get:s[i],enumerable:!0})},l=(t,s,i,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of m(s))!g.call(t,r)&&r!==i&&c(t,r,{get:()=>s[r],enumerable:!(e=b(s,r))||e.enumerable});return t};var v=t=>l(c({},"__esModule",{value:!0}),t);var y={};h(y,{MemoryMessageProvider:()=>n,Qified:()=>a,QifiedEvents:()=>d});module.exports=v(y);var p=require("hookified");var P="@qified/memory",n=class{_subscriptions;_id;constructor(s){this._subscriptions=new Map,this._id=s?.id??P}get id(){return this._id}set id(s){this._id=s}get subscriptions(){return this._subscriptions}set subscriptions(s){this._subscriptions=s}async publish(s,i){let e={...i,providerId:this._id},r=this._subscriptions.get(s)??[];for(let u of r)await u.handler(e)}async subscribe(s,i){this._subscriptions.has(s)||this._subscriptions.set(s,[]),this._subscriptions.get(s)?.push(i)}async unsubscribe(s,i){if(i){let e=this._subscriptions.get(s);e&&this._subscriptions.set(s,e.filter(r=>r.id!==i))}else this._subscriptions.delete(s)}async disconnect(){this._subscriptions.clear()}};var d=(o=>(o.error="error",o.info="info",o.warn="warn",o.publish="publish",o.subscribe="subscribe",o.unsubscribe="unsubscribe",o.disconnect="disconnect",o))(d||{}),a=class extends p.Hookified{_messageProviders=[];constructor(s){super(s),s?.messageProviders&&(this._messageProviders=s.messageProviders)}get messageProviders(){return this._messageProviders}set messageProviders(s){this._messageProviders=s}async subscribe(s,i){try{let e=this._messageProviders.map(async r=>r.subscribe(s,i));await Promise.all(e),this.emit("subscribe",{topic:s,handler:i})}catch(e){this.emit("error",e)}}async publish(s,i){try{let e=this._messageProviders.map(async r=>r.publish(s,i));await Promise.all(e),this.emit("publish",{topic:s,message:i})}catch(e){this.emit("error",e)}}async unsubscribe(s,i){try{let e=this._messageProviders.map(async r=>r.unsubscribe(s,i));await Promise.all(e),this.emit("unsubscribe",{topic:s,id:i})}catch(e){this.emit("error",e)}}async disconnect(){try{let s=this._messageProviders.map(async i=>i.disconnect());await Promise.all(s),this._messageProviders=[],this.emit("disconnect")}catch(s){this.emit("error",s)}}};0&&(module.exports={MemoryMessageProvider,Qified,QifiedEvents});
+92
-7

@@ -0,1 +1,3 @@

import { HookifiedOptions, Hookified } from 'hookified';
/**

@@ -12,2 +14,6 @@ * Message interface for the message provider

/**
* the provider that passed the message
*/
providerId: string;
/**
* The data of the message

@@ -37,2 +43,7 @@ * @type {<T = any>}

/**
* The id of the message provider. Use primary when multiple providers
* are used.
*/
id: string;
/**
* Array of handlers for message processing

@@ -48,3 +59,3 @@ * @type {Map<string, Array<TopicHandler>>}

*/
publish(topic: string, message: Message): Promise<void>;
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**

@@ -139,13 +150,87 @@ * Subscribe to a topic / queue. This is used to receive messages from the provider.

/**
* Configuration options for the memory message provider.
*/
type MemoryMessageProviderOptions = {
/**
* The unique identifier for this provider instance.
* @default "@qified/memory"
*/
id?: string;
};
/**
* In-memory message provider for testing and simple use cases.
* Messages are stored and delivered synchronously in memory without persistence.
*/
declare class MemoryMessageProvider implements MessageProvider {
private _subscriptions;
constructor();
private _id;
/**
* Creates an instance of MemoryMessageProvider.
* @param {MemoryMessageProviderOptions} options - Optional configuration for the provider.
*/
constructor(options?: MemoryMessageProviderOptions);
/**
* Gets the provider ID for the memory message provider.
* @returns {string} The provider ID.
*/
get id(): string;
/**
* Sets the provider ID for the memory message provider.
* @param {string} id The new provider ID.
*/
set id(id: string);
/**
* Gets the subscriptions map for all topics.
* @returns {Map<string, TopicHandler[]>} The subscriptions map.
*/
get subscriptions(): Map<string, TopicHandler[]>;
/**
* Sets the subscriptions map.
* @param {Map<string, TopicHandler[]>} value The new subscriptions map.
*/
set subscriptions(value: Map<string, TopicHandler[]>);
publish(topic: string, message: Message): Promise<void>;
/**
* Publishes a message to a specified topic.
* All handlers subscribed to the topic will be called synchronously in order.
* @param {string} topic The topic to publish the message to.
* @param {Message} message The message to publish.
* @returns {Promise<void>} A promise that resolves when all handlers have been called.
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Subscribes to a specified topic.
* @param {string} topic The topic to subscribe to.
* @param {TopicHandler} handler The handler to process incoming messages.
* @returns {Promise<void>} A promise that resolves when the subscription is complete.
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Unsubscribes from a specified topic.
* If an ID is provided, only the handler with that ID is removed.
* If no ID is provided, all handlers for the topic are removed.
* @param {string} topic The topic to unsubscribe from.
* @param {string} [id] Optional identifier for the subscription to remove.
* @returns {Promise<void>} A promise that resolves when the unsubscription is complete.
*/
unsubscribe(topic: string, id?: string): Promise<void>;
/**
* Disconnects and clears all subscriptions.
* @returns {Promise<void>} A promise that resolves when the disconnection is complete.
*/
disconnect(): Promise<void>;
}
/**
* Standard events emitted by Qified.
*/
declare enum QifiedEvents {
error = "error",
info = "info",
warn = "warn",
publish = "publish",
subscribe = "subscribe",
unsubscribe = "unsubscribe",
disconnect = "disconnect"
}
type QifiedOptions = {

@@ -160,4 +245,4 @@ /**

taskProviders?: TaskProvider[];
};
declare class Qified {
} & HookifiedOptions;
declare class Qified extends Hookified {
private _messageProviders;

@@ -190,3 +275,3 @@ /**

*/
publish(topic: string, message: Message): Promise<void>;
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**

@@ -206,2 +291,2 @@ * Unsubscribes from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.

export { MemoryMessageProvider, type Message, type MessageProvider, Qified, type QifiedOptions, type TaskProvider, type TopicHandler };
export { MemoryMessageProvider, type Message, type MessageProvider, Qified, QifiedEvents, type QifiedOptions, type TaskProvider, type TopicHandler };

@@ -0,1 +1,3 @@

import { HookifiedOptions, Hookified } from 'hookified';
/**

@@ -12,2 +14,6 @@ * Message interface for the message provider

/**
* the provider that passed the message
*/
providerId: string;
/**
* The data of the message

@@ -37,2 +43,7 @@ * @type {<T = any>}

/**
* The id of the message provider. Use primary when multiple providers
* are used.
*/
id: string;
/**
* Array of handlers for message processing

@@ -48,3 +59,3 @@ * @type {Map<string, Array<TopicHandler>>}

*/
publish(topic: string, message: Message): Promise<void>;
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**

@@ -139,13 +150,87 @@ * Subscribe to a topic / queue. This is used to receive messages from the provider.

/**
* Configuration options for the memory message provider.
*/
type MemoryMessageProviderOptions = {
/**
* The unique identifier for this provider instance.
* @default "@qified/memory"
*/
id?: string;
};
/**
* In-memory message provider for testing and simple use cases.
* Messages are stored and delivered synchronously in memory without persistence.
*/
declare class MemoryMessageProvider implements MessageProvider {
private _subscriptions;
constructor();
private _id;
/**
* Creates an instance of MemoryMessageProvider.
* @param {MemoryMessageProviderOptions} options - Optional configuration for the provider.
*/
constructor(options?: MemoryMessageProviderOptions);
/**
* Gets the provider ID for the memory message provider.
* @returns {string} The provider ID.
*/
get id(): string;
/**
* Sets the provider ID for the memory message provider.
* @param {string} id The new provider ID.
*/
set id(id: string);
/**
* Gets the subscriptions map for all topics.
* @returns {Map<string, TopicHandler[]>} The subscriptions map.
*/
get subscriptions(): Map<string, TopicHandler[]>;
/**
* Sets the subscriptions map.
* @param {Map<string, TopicHandler[]>} value The new subscriptions map.
*/
set subscriptions(value: Map<string, TopicHandler[]>);
publish(topic: string, message: Message): Promise<void>;
/**
* Publishes a message to a specified topic.
* All handlers subscribed to the topic will be called synchronously in order.
* @param {string} topic The topic to publish the message to.
* @param {Message} message The message to publish.
* @returns {Promise<void>} A promise that resolves when all handlers have been called.
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Subscribes to a specified topic.
* @param {string} topic The topic to subscribe to.
* @param {TopicHandler} handler The handler to process incoming messages.
* @returns {Promise<void>} A promise that resolves when the subscription is complete.
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Unsubscribes from a specified topic.
* If an ID is provided, only the handler with that ID is removed.
* If no ID is provided, all handlers for the topic are removed.
* @param {string} topic The topic to unsubscribe from.
* @param {string} [id] Optional identifier for the subscription to remove.
* @returns {Promise<void>} A promise that resolves when the unsubscription is complete.
*/
unsubscribe(topic: string, id?: string): Promise<void>;
/**
* Disconnects and clears all subscriptions.
* @returns {Promise<void>} A promise that resolves when the disconnection is complete.
*/
disconnect(): Promise<void>;
}
/**
* Standard events emitted by Qified.
*/
declare enum QifiedEvents {
error = "error",
info = "info",
warn = "warn",
publish = "publish",
subscribe = "subscribe",
unsubscribe = "unsubscribe",
disconnect = "disconnect"
}
type QifiedOptions = {

@@ -160,4 +245,4 @@ /**

taskProviders?: TaskProvider[];
};
declare class Qified {
} & HookifiedOptions;
declare class Qified extends Hookified {
private _messageProviders;

@@ -190,3 +275,3 @@ /**

*/
publish(topic: string, message: Message): Promise<void>;
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**

@@ -206,2 +291,2 @@ * Unsubscribes from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.

export { MemoryMessageProvider, type Message, type MessageProvider, Qified, type QifiedOptions, type TaskProvider, type TopicHandler };
export { MemoryMessageProvider, type Message, type MessageProvider, Qified, QifiedEvents, type QifiedOptions, type TaskProvider, type TopicHandler };

@@ -1,118 +0,1 @@

// src/memory/message.ts
var MemoryMessageProvider = class {
_subscriptions;
constructor() {
this._subscriptions = /* @__PURE__ */ new Map();
}
get subscriptions() {
return this._subscriptions;
}
set subscriptions(value) {
this._subscriptions = value;
}
async publish(topic, message) {
const subscriptions = this._subscriptions.get(topic) ?? [];
for (const subscription of subscriptions) {
await subscription.handler(message);
}
}
async subscribe(topic, handler) {
if (!this._subscriptions.has(topic)) {
this._subscriptions.set(topic, []);
}
this._subscriptions.get(topic)?.push(handler);
}
async unsubscribe(topic, id) {
if (id) {
const subscriptions = this._subscriptions.get(topic);
if (subscriptions) {
this._subscriptions.set(
topic,
subscriptions.filter((sub) => sub.id !== id)
);
}
} else {
this._subscriptions.delete(topic);
}
}
async disconnect() {
this._subscriptions.clear();
}
};
// src/index.ts
var Qified = class {
_messageProviders = [];
/**
* Creates an instance of Qified.
* @param {QifiedOptions} options - Optional configuration for Qified.
*/
constructor(options) {
if (options?.messageProviders) {
this._messageProviders = options.messageProviders;
}
}
/**
* Gets or sets the message providers.
* @returns {MessageProvider[]} The array of message providers.
*/
get messageProviders() {
return this._messageProviders;
}
/**
* Sets the message providers.
* @param {MessageProvider[]} providers - The array of message providers to set.
*/
set messageProviders(providers) {
this._messageProviders = providers;
}
/**
* Subscribes to a topic. If you have multiple message providers, it will subscribe to the topic on all of them.
* @param {string} topic - The topic to subscribe to.
* @param {TopicHandler} handler - The handler to call when a message is published to the topic.
*/
async subscribe(topic, handler) {
const promises = this._messageProviders.map(
async (provider) => provider.subscribe(topic, handler)
);
await Promise.all(promises);
}
/**
* Publishes a message to a topic. If you have multiple message providers, it will publish the message to all of them.
* @param {string} topic - The topic to publish to.
* @param {Message} message - The message to publish.
*/
async publish(topic, message) {
const promises = this._messageProviders.map(
async (provider) => provider.publish(topic, message)
);
await Promise.all(promises);
}
/**
* Unsubscribes from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the topic.
* @param topic - The topic to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the topic will be unsubscribed.
*/
async unsubscribe(topic, id) {
const promises = this._messageProviders.map(
async (provider) => provider.unsubscribe(topic, id)
);
await Promise.all(promises);
}
/**
* Disconnects from all providers.
* This method will call the `disconnect` method on each message provider.
*/
async disconnect() {
const promises = this._messageProviders.map(
async (provider) => provider.disconnect()
);
await Promise.all(promises);
this._messageProviders = [];
}
};
export {
MemoryMessageProvider,
Qified
};
import{Hookified as d}from"hookified";var p="@qified/memory",o=class{_subscriptions;_id;constructor(s){this._subscriptions=new Map,this._id=s?.id??p}get id(){return this._id}set id(s){this._id=s}get subscriptions(){return this._subscriptions}set subscriptions(s){this._subscriptions=s}async publish(s,i){let e={...i,providerId:this._id},r=this._subscriptions.get(s)??[];for(let a of r)await a.handler(e)}async subscribe(s,i){this._subscriptions.has(s)||this._subscriptions.set(s,[]),this._subscriptions.get(s)?.push(i)}async unsubscribe(s,i){if(i){let e=this._subscriptions.get(s);e&&this._subscriptions.set(s,e.filter(r=>r.id!==i))}else this._subscriptions.delete(s)}async disconnect(){this._subscriptions.clear()}};var u=(t=>(t.error="error",t.info="info",t.warn="warn",t.publish="publish",t.subscribe="subscribe",t.unsubscribe="unsubscribe",t.disconnect="disconnect",t))(u||{}),n=class extends d{_messageProviders=[];constructor(s){super(s),s?.messageProviders&&(this._messageProviders=s.messageProviders)}get messageProviders(){return this._messageProviders}set messageProviders(s){this._messageProviders=s}async subscribe(s,i){try{let e=this._messageProviders.map(async r=>r.subscribe(s,i));await Promise.all(e),this.emit("subscribe",{topic:s,handler:i})}catch(e){this.emit("error",e)}}async publish(s,i){try{let e=this._messageProviders.map(async r=>r.publish(s,i));await Promise.all(e),this.emit("publish",{topic:s,message:i})}catch(e){this.emit("error",e)}}async unsubscribe(s,i){try{let e=this._messageProviders.map(async r=>r.unsubscribe(s,i));await Promise.all(e),this.emit("unsubscribe",{topic:s,id:i})}catch(e){this.emit("error",e)}}async disconnect(){try{let s=this._messageProviders.map(async i=>i.disconnect());await Promise.all(s),this._messageProviders=[],this.emit("disconnect")}catch(s){this.emit("error",s)}}};export{o as MemoryMessageProvider,n as Qified,u as QifiedEvents};
{
"name": "qified",
"version": "0.4.3",
"version": "0.5.0",
"description": "Task and Message Queues with Multiple Providers",

@@ -36,7 +36,7 @@ "type": "module",

"devDependencies": {
"@biomejs/biome": "^2.2.4",
"@biomejs/biome": "^2.2.5",
"@vitest/coverage-v8": "^3.2.4",
"rimraf": "^6.0.1",
"tsup": "^8.5.0",
"typescript": "^5.9.2",
"typescript": "^5.9.3",
"vitest": "^3.2.4"

@@ -48,2 +48,5 @@ },

],
"dependencies": {
"hookified": "^1.12.1"
},
"scripts": {

@@ -54,5 +57,5 @@ "lint": "biome check --write --error-on-warnings",

"clean": "rimraf ./dist ./coverage ./site/dist",
"build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
"build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean --minify",
"build:publish": "pnpm build && pnpm publish --access public --no-git-checks"
}
}
+293
-6

@@ -20,13 +20,300 @@ [![logo.svg](https://qified.org/logo.svg)](https://qified.org)

* Easily Subscribe to a message Queue `subscribe()`
* Simple Task Format `Task`
* Easily Send a Task `enqueue()`
* Easily Subscribe to a Task Queue `dequeue()`
* Simple Acknowledge `Acknowledge()` in handler
* Simple Task Format `Task` (Coming in v1.0.0)
* Easily Send a Task `enqueue()` (Coming in v1.0.0)
* Easily Subscribe to a Task Queue `dequeue()` (Coming in v1.0.0)
* Simple Acknowledge `Acknowledge()` in handler (Coming in v1.0.0)
* Async/Await Built In By Default
* Written in Typescript, Nodejs Last Two Versions, ESM and CJS
* Events and Hooks for all major actions via [Hookified](https://hookified.org)
* Customizable Serialize / Deserialize Handlers
* Customizable Compress / Decompress Handlers
* Customizable Serialize / Deserialize Handlers (Coming in v1.0.0)
* Customizable Compress / Decompress Handlers (Coming in v1.0.0)
* Provider Fail Over Support
# Installation
```bash
pnpm add qified
```
# Quick Start
```js
import { Qified, MemoryMessageProvider } from 'qified';
// Create a new Qified instance with a memory provider
const qified = new Qified({
messageProviders: [new MemoryMessageProvider()]
});
// Subscribe to a topic
await qified.subscribe('notifications', {
id: 'notificationHandler',
handler: async (message) => {
console.log('Received:', message.data);
}
});
// Publish a message
await qified.publish('notifications', {
id: 'msg-1',
data: { text: 'Hello, World!' }
});
// Clean up
await qified.disconnect();
```
# Constructor
```js
new Qified(options?: QifiedOptions)
```
**Options:**
- `messageProviders?: MessageProvider[]` - Array of message providers to use
- `taskProviders?: TaskProvider[]` - Array of task providers to use
**Example:**
```js
import { Qified, MemoryMessageProvider } from 'qified';
const qified = new Qified({
messageProviders: [new MemoryMessageProvider()]
});
```
# Properties
### `messageProviders: MessageProvider[]`
Get or set the array of message providers. This property allows you to dynamically manage which message providers are active in your Qified instance.
**Type:** `MessageProvider[]`
**Access:** Read/Write
**Description:**
- **Getter**: Returns the current array of message providers being used
- **Setter**: Replaces all current message providers with a new array
**Use Cases:**
- Inspect which providers are currently configured
- Add or remove providers dynamically at runtime
- Replace all providers with a new set
- Migrate from one provider to another
**Example:**
```typescript
import { Qified, MemoryMessageProvider } from 'qified';
import { NatsMessageProvider } from '@qified/nats';
import { RedisMessageProvider } from '@qified/redis';
const qified = new Qified({
messageProviders: [new MemoryMessageProvider()]
});
// Get current providers
const providers = qified.messageProviders;
console.log(`Currently using ${providers.length} provider(s)`);
// Add another provider
qified.messageProviders = [
new MemoryMessageProvider(),
new NatsMessageProvider()
];
// Replace all providers
qified.messageProviders = [
new RedisMessageProvider({ uri: 'redis://localhost:6379' })
];
// Access provider properties
qified.messageProviders.forEach(provider => {
console.log('Provider ID:', provider.id);
});
```
**Important Notes:**
- Setting this property does **not** automatically disconnect existing providers
- You should call `disconnect()` on old providers before replacing them to clean up resources
- All operations (`subscribe`, `publish`, `unsubscribe`) will execute across all providers in this array
# Methods
## subscribe
Subscribe to a topic to receive messages. If multiple message providers are configured, this will subscribe on all of them.
**Parameters:**
- `topic: string` - The topic to subscribe to
- `handler: TopicHandler` - Object containing an optional `id` and a `handler` function
**Example:**
```js
await qified.subscribe('user-events', {
id: 'userEventHandler',
handler: async (message) => {
console.log('User event:', message.data);
}
});
```
## publish
Publish a message to a topic. If multiple message providers are configured, this will publish to all of them.
**Parameters:**
- `topic: string` - The topic to publish to
- `message: Message` - The message object to publish
**Example:**
```js
await qified.publish('user-events', {
id: 'evt-123',
data: {
userId: 'user-456',
action: 'login',
timestamp: Date.now()
},
headers: {
'content-type': 'application/json'
}
});
```
## unsubscribe
Unsubscribe from a topic. If an `id` is provided, only that handler is unsubscribed. Otherwise, all handlers for the topic are unsubscribed.
**Parameters:**
- `topic: string` - The topic to unsubscribe from
- `id?: string` - Optional handler ID. If not provided, all handlers are unsubscribed
**Example:**
```js
// Unsubscribe a specific handler
await qified.unsubscribe('user-events', 'userEventHandler');
// Unsubscribe all handlers for a topic
await qified.unsubscribe('user-events');
```
## disconnect`
Disconnect from all providers and clean up resources.
**Example:**
```js
await qified.disconnect();
```
# Events
Qified extends [Hookified](https://hookified.org) and emits events for all major operations. You can listen to these events to add custom logging, monitoring, or error handling.
# Available Events
The following events are available via the `QifiedEvents` enum:
- `QifiedEvents.publish` - Emitted after a message is successfully published
- `QifiedEvents.subscribe` - Emitted after successfully subscribing to a topic
- `QifiedEvents.unsubscribe` - Emitted after successfully unsubscribing from a topic
- `QifiedEvents.disconnect` - Emitted after successfully disconnecting from all providers
- `QifiedEvents.error` - Emitted when an error occurs during any operation
- `QifiedEvents.info` - Emitted for informational messages
- `QifiedEvents.warn` - Emitted for warning messages
# Listening to Events
Use the `on()` method to listen to events:
```js
import { Qified, MemoryMessageProvider, QifiedEvents } from 'qified';
const qified = new Qified({
messageProviders: [new MemoryMessageProvider()]
});
// Listen for publish events
await qified.on(QifiedEvents.publish, async (data) => {
console.log('Message published to topic:', data.topic);
console.log('Message:', data.message);
});
// Listen for subscribe events
await qified.on(QifiedEvents.subscribe, async (data) => {
console.log('Subscribed to topic:', data.topic);
console.log('Handler ID:', data.handler.id);
});
// Listen for unsubscribe events
await qified.on(QifiedEvents.unsubscribe, async (data) => {
console.log('Unsubscribed from topic:', data.topic);
if (data.id) {
console.log('Handler ID:', data.id);
}
});
// Listen for disconnect events
await qified.on(QifiedEvents.disconnect, async () => {
console.log('Disconnected from all providers');
});
// Listen for errors
await qified.on(QifiedEvents.error, async (error) => {
console.error('Error occurred:', error);
});
// Now perform operations
await qified.subscribe('events', {
id: 'handler1',
handler: async (message) => {
console.log('Received:', message.data);
}
});
await qified.publish('events', {
id: 'msg-1',
data: { text: 'Hello!' }
});
await qified.unsubscribe('events', 'handler1');
await qified.disconnect();
```
### Error Handling with Events
Events provide a centralized way to handle errors across all operations:
```js
import { Qified, QifiedEvents } from 'qified';
import { NatsMessageProvider } from '@qified/nats';
const qified = new Qified({
messageProviders: [new NatsMessageProvider()]
});
// Centralized error handler
await qified.on(QifiedEvents.error, async (error) => {
console.error('Qified error:', error.message);
// Send to error tracking service
// Log to file
// Send alert
});
// Errors from publish, subscribe, etc. will be caught and emitted
await qified.publish('topic', { id: '1', data: { test: true } });
```
# Providers
There are multiple providers available to use:
* Memory - this is built into the current `qified` library as `MemoryMessageProvider`.
* [@qified/redis](packages/redis/README.md) - Redis Provider
* [@qified/rabbitmq](packages/rabbitmq/README.md) - RabbitMQ Provider
* [@qified/nats](packages/nats/README.md) - NATS Provider
* [@qified/zeromq](packages/zeromq/README.md) - ZeroMQ Provider
# Development and Testing

@@ -33,0 +320,0 @@