From e8d858d1b418acc057c09d5acf0505c8f7499066 Mon Sep 17 00:00:00 2001 From: andresfv95 Date: Mon, 3 Feb 2025 10:10:16 -0500 Subject: [PATCH] feat: update docs and standardization of methods in ApiClient (#75) Co-authored-by: Ariel Gentile --- examples/chatbot/index.ts | 4 +- examples/verifier/index.ts | 2 +- packages/client/README.md | 131 ++++++++++++++++++ packages/client/src/ApiClient.ts | 18 +-- packages/model/README.md | 93 +++++++++++++ packages/nestjs-client/README.md | 112 ++++++++++++++- .../src/credentials/credential.service.ts | 2 +- 7 files changed, 343 insertions(+), 19 deletions(-) create mode 100644 packages/client/README.md create mode 100644 packages/model/README.md diff --git a/examples/chatbot/index.ts b/examples/chatbot/index.ts index 77a8aad..c715666 100644 --- a/examples/chatbot/index.ts +++ b/examples/chatbot/index.ts @@ -105,8 +105,8 @@ const server = app.listen(PORT, async () => { logger.info(`phoneNumberCredentialDefinitionId: ${phoneNumberCredentialDefinitionId}`) phoneNumberRevocationDefinitionId = - (await apiClient.revocationRegistry.get(phoneNumberCredentialDefinitionId))[0] ?? - (await apiClient.revocationRegistry.create({ + (await apiClient.revocationRegistries.get(phoneNumberCredentialDefinitionId))[0] ?? + (await apiClient.revocationRegistries.create({ credentialDefinitionId: phoneNumberCredentialDefinitionId, maximumCredentialNumber: 1000, })) diff --git a/examples/verifier/index.ts b/examples/verifier/index.ts index ea4118b..0ca3afe 100644 --- a/examples/verifier/index.ts +++ b/examples/verifier/index.ts @@ -55,7 +55,7 @@ expressHandler.messageReceived(async (req, res) => { app.get('/invitation/:ref', async (req, res) => { logger.info(`Generate invitation`) - const presReq = await apiClient.invitation.createPresentationRequest({ + const presReq = await apiClient.invitations.createPresentationRequest({ ref: req.params.ref, callbackUrl: `${PUBLIC_BASE_URL}/presentation`, requestedCredentials: [ diff --git a/packages/client/README.md b/packages/client/README.md new file mode 100644 index 0000000..f1744e8 --- /dev/null +++ b/packages/client/README.md @@ -0,0 +1,131 @@ +`@2060.io/service-agent-client` + +# Service Agent Client +**Service Agent Client** is a TypeScript library designed to simplify the interaction with **Service Agent** (`@2060.io/service-agent-main`). It provides an abstraction layer for communicating with the agent, handling messaging, credential management, and event handling efficiently. + +This package ensures that the client stays updated with the latest API versioning of the **Service Agent** to maintain compatibility with evolving endpoints. + +## Features +- **Simplified API interaction:** Provides an easy-to-use client to interact with the Service Agent. +- **Event handling:** Includes an ExpressEventHandler for quick integration into Express-based applications. +- **Service-based structure:** Dedicated services for messaging, credentials, invitations, and revocation registries. +- **Versioning support:** Supports API versioning to maintain compatibility with different Service Agent versions. + +## Repository +Find the public repository here: [2060 Service Agent](../../README.md) + +## How to work +```plantuml +@startuml + +package "2060 Ecosystem" { + package "Service Agent (SA)" { + class ServiceAgent { + + Handles DIDComm communication + + Manages agent wallet and credentials + + Exposes API for client interactions + } + } + + package "Libraries" { + class NestJSClient { + + Plug-and-play integration + + Selectable modules for various services + + Modules: + -- MessageEventOptions: Configures message event handling + -- ConnectionEventOptions: Configures connection event handling + -- CredentialOptions: Configures credential management + } + class Client ##red { + + Directly manages requests to SA + + Facilitates reception of requests from modules + + Provides an abstraction for service communication + + Interfaces: + -- messages + -- credentialTypes + -- revocationRegistries + -- invitations + + } + class ModelLibrary { + + Defines required data models + + Ensures type safety across services + } + } +} + +NestJSClient --> ServiceAgent : Uses +Client --> ServiceAgent : Sends requests +Client --> ServiceAgent : Receives requests +Client --> ModelLibrary : Uses models +ModelLibrary --> ServiceAgent : Provides data models +NestJSClient --> ModelLibrary : Uses models + +@enduml +``` + +## Installation +```sh +npm install @2060.io/service-agent-client +``` +or +```sh +yarn add @2060.io/service-agent-client +``` +## `ApiClient.ts` +`ApiClient` class provides a simple interface for interacting with the Service Agent. It abstracts API calls and offers dedicated service methods for messaging, credential types, invitations, and revocation registries. + +### Example Usage +```ts +import { ApiClient, ApiVersion } from '@2060.io/service-agent-client' + +const apiClient = new ApiClient('http://localhost:3000', ApiVersion.V1) + +// Sending a message +const messageId = await apiClient.messages.send( + new TextMessage({ + connectionId: 'connectionId', + content: 'Hello, world!', + }) +) + +console.log(`Message sent with ID: ${messageId}`) +``` + +### Services +- `messages:` Handles message sending and receiving. +- `credentialTypes:` Manages credential types. +- `revocationRegistries:` Manages revocation registries. +- `invitations:` Handles connection invitations. + +## `ExpressEventHandler.ts` +The `ExpressEventHandler` simplifies event handling for Express applications, mapping API endpoints to event handlers. +### Example Usage +```ts +import express from 'express' +import { ExpressEventHandler } from '@2060.io/service-agent-client' + +const app = express() +const eventHandler = new ExpressEventHandler(app) + +expressHandler.messageStateUpdated(async (req, res) => { + const obj = req.body + logger.info(`message state updated: ${JSON.stringify(obj)}`) + res.json({ message: 'ok' }) +}) + +app.listen(3000, () => console.log('Server running on port 3000')) +``` +### Available Event Handlers +- `connectionStateUpdated` (`POST /connection-state-updated`) +- `messageStateUpdated` (`POST /message-state-updated`) +- `messageReceived` (`POST /message-received`) + +## Contributing +This library evolves alongside the Service Agent. Contributions are welcome! +- Fork the repository. +- Create a feature branch. +- Commit changes. +- Open a pull request. + +For more details, visit the [official repository](https://github.com/2060-io/2060-service-agent). \ No newline at end of file diff --git a/packages/client/src/ApiClient.ts b/packages/client/src/ApiClient.ts index c8423f0..a6a51b1 100644 --- a/packages/client/src/ApiClient.ts +++ b/packages/client/src/ApiClient.ts @@ -25,29 +25,29 @@ import { ApiVersion } from './types/enums' * const apiClient = new ApiClient('http://localhost', ApiVersion.V1) * * // Example to query available credentials - * await apiClient.credentialType.getAll() + * await apiClient.credentialTypes.getAll() * * // Example to send a message - * apiClient.message.send(message: BaseMessage) + * apiClient.messages.send(message: BaseMessage) * * The `ApiClient` class provides easy methods for interacting with: - * - `message`: Send and manage messages. - * - `credentialType`: Query and manage credential types. - * - `revocationRegistry`: Query and manage the revocation registry for credential definitions. + * - `messages`: Send and manage messages. + * - `credentialTypes`: Query and manage credential types. + * - `revocationRegistries`: Query and manage the revocation registry for credential definitions. */ export class ApiClient { public readonly messages: MessageService public readonly credentialTypes: CredentialTypeService - public readonly revocationRegistry: RevocationRegistryService - public readonly invitation: InvitationService + public readonly revocationRegistries: RevocationRegistryService + public readonly invitations: InvitationService constructor( private baseURL: string, private version: ApiVersion = ApiVersion.V1, ) { - this.invitation = new InvitationService(baseURL, version) + this.invitations = new InvitationService(baseURL, version) this.messages = new MessageService(baseURL, version) this.credentialTypes = new CredentialTypeService(baseURL, version) - this.revocationRegistry = new RevocationRegistryService(baseURL, version) + this.revocationRegistries = new RevocationRegistryService(baseURL, version) } } diff --git a/packages/model/README.md b/packages/model/README.md new file mode 100644 index 0000000..0b68a25 --- /dev/null +++ b/packages/model/README.md @@ -0,0 +1,93 @@ +`@2060.io/service-agent-model` +# Service Agent Model + +This package provides the data models used by **Service Agent** and its related services and libraries within the `@2060.io` ecosystem. These models are essential for chatbot development and facilitate integration with the broader system. + +## Packages Using This Library + +The models in this package are used by the following services and libraries: + +- **[@2060.io/service-agent-main](../../README.md)** – The core Service Agent. +- **[@2060.io/service-agent-nestjs-client](../nestjs-client/README.md)** – A NestJS client for interacting with the Service Agent. +- **[@2060.io/service-agent-client](../client/README.md)** – A general-purpose api client for the Service Agent. + + +## Usage + +This package defines essential models that support structured communication and event handling within the Service Agent ecosystem. It is designed to be used by chatbot services and other integrations that rely on a standardized message format. + +## How to work +```plantuml +@startuml + +package "2060 Ecosystem" { + package "Service Agent (SA)" { + class ServiceAgent { + + Handles DIDComm communication + + Manages agent wallet and credentials + + Exposes API for client interactions + } + } + + package "Libraries" { + class NestJSClient { + + Plug-and-play integration + + Selectable modules for various services + + Modules: + -- MessageEventOptions: Configures message event handling + -- ConnectionEventOptions: Configures connection event handling + -- CredentialOptions: Configures credential management + } + class Client { + + Directly manages requests to SA + + Facilitates reception of requests from modules + + Provides an abstraction for service communication + + Interfaces: + -- messages + -- credentialTypes + -- revocationRegistries + -- invitations + + } + class ModelLibrary ##red { + + Defines required data models + + Ensures type safety across services + } + } +} + +NestJSClient --> ServiceAgent : Uses +Client --> ServiceAgent : Sends requests +Client --> ServiceAgent : Receives requests +Client --> ModelLibrary : Uses models +ModelLibrary --> ServiceAgent : Provides data models +NestJSClient --> ModelLibrary : Uses models + +@enduml +``` + +### Installation + +```sh +npm install @2060.io/service-agent-model +``` +or +```sh +yarn add @2060.io/service-agent-model +``` + +## Example + +Importing and using a message model: + +```typescript +import { CallOfferRequestMessage } from '@2060.io/service-agent-model'; + +const callOffer = new CallOfferRequestMessage({ + connectionId: 'connectionId', + description: 'Start call', + parameters: { wsUrl, roomId, peerId }, +}); + +console.log(callOffer); +``` diff --git a/packages/nestjs-client/README.md b/packages/nestjs-client/README.md index 3ad7f82..1614940 100644 --- a/packages/nestjs-client/README.md +++ b/packages/nestjs-client/README.md @@ -1,8 +1,109 @@ +`@2060.io/service-agent-nestjs-client` # Nestjs-client for Service Agent -The `nestjs-client` library is designed to manage recurring components for chatbots developed using the [2060 Service Agent](../../README.md). Its modules follow a plug-and-play architecture, allowing developers to include them as needed. However, certain modules, such as credential management, recommend incorporating the message handling module to function correctly. +The `nestjs-client` library simplifies the integration of 2060 Service Agent components in your NestJS applications. It provides several modules that follow a plug-and-play architecture, allowing you to incorporate them based on your needs. Certain modules, such as credential management, recommend using the message handling module for seamless operation. -**Example of Using Independent Modules:** +## Available Modules +1. Message Handling: + - Manages the events related to message states, including when a message is sent, delivered, or received. + - Use this module if you're integrating messaging functionality into your application. +2. Credential Management: + - Handles the lifecycle of credentials, including offering, accepting, rejecting, and revoking credentials. + - This module is typically used when you need to manage digital credentials for your application. +3. Connection Management: + - Manages events related to connection state changes. +## How to work +```plantuml +@startuml + +package "2060 Ecosystem" { + package "Service Agent (SA)" { + class ServiceAgent { + + Handles DIDComm communication + + Manages agent wallet and credentials + + Exposes API for client interactions + } + } + + package "Libraries" { + class NestJSClient ##red { + + Plug-and-play integration + + Selectable modules for various services + + Modules: + -- MessageEventOptions: Configures message event handling + -- ConnectionEventOptions: Configures connection event handling + -- CredentialOptions: Configures credential management + } + class Client { + + Directly manages requests to SA + + Facilitates reception of requests from modules + + Provides an abstraction for service communication + + Interfaces: + -- messages + -- credentialTypes + -- revocationRegistries + -- invitations + + } + class ModelLibrary { + + Defines required data models + + Ensures type safety across services + } + } +} + +NestJSClient --> ServiceAgent : Uses +Client --> ServiceAgent : Sends requests +Client --> ServiceAgent : Receives requests +Client --> ModelLibrary : Uses models +ModelLibrary --> ServiceAgent : Provides data models +NestJSClient --> ModelLibrary : Uses models + +@enduml +``` + +## Configuration +### Dynamic Module Setup +The `nestjs-client` allows dynamic configuration through various module options defined in `types.ts`. You can configure individual modules or the `EventsModule` for handling multiple events at once +### Key Configuration Options +- `eventHandler`: Specifies the event handler class to handle incoming events. It must implement the `EventHandler` interface. +- `imports`: An array of additional modules to import, such as service modules or other shared functionality. +- `url`: The URL of the service agent for connecting to it. +- `version`: Specifies the version of the service agent API to use. + +#### `MessageEventOptions` +Configures message event handling. The following properties are available: +- `eventHandler` (optional). +- `imports` (optional). +- `url` (mandatory). +- `version` (optional). +#### `ConnectionEventOptions` +Configures connection event handling. The following properties are available: +- `eventHandler` (optional). +- `imports` (optional). + +#### `CredentialOptions` +Configures credential management. The following properties are available: +- `imports` (optional). +- `url` (mandatory). +- `version` (optional). + +#### `ModulesConfig` +This interface defines the configuration for enabling or disabling modules: +- `messages` (optional): Whether to enable the message handling module. Defaults to false. +- `connections` (optional): Whether to enable the connection management module. Defaults to false. +- `credentials` (optional): Whether to enable the credential management module. Defaults to false. + +#### `EventsModuleOptions` +This configuration interface is used to configure multiple modules at once via the EventsModule: +- `modules`: Specifies which modules to enable (messages, connections, and credentials). +- `options`: Contains common configuration options that apply to each module, such as eventHandler, imports, url, and version. + + + + +### Example of Using Independent Modules +This example demonstrates how to use each module separately: ```typescript @Module({ imports: [ @@ -20,8 +121,8 @@ The `nestjs-client` library is designed to manage recurring components for chatb export class AppModule {} ``` -**Example of Using the Recommended `EventsModule`:** - +### Example of Using the Recommended `EventsModule` +The recommended approach is to use the `EventsModule` to register multiple modules at once for easier configuration: ```typescript @Module({ imports: [ @@ -41,7 +142,6 @@ export class AppModule {} }) export class AppModule {} ``` - -In the first example, individual modules like `MessageEventModule` and `CredentialManagementModule` are configured separately. In the second example, the `EventsModule` is used to register multiple modules simultaneously, which is the recommended approach for streamlined configuration and better integration. +In this example, the `EventsModule` is used to register multiple modules simultaneously, which ensures better integration and streamlined configuration for common use cases. For more information on dynamic modules and their configuration in NestJS, refer to the official [documentation](https://docs.nestjs.com/fundamentals/dynamic-modules) \ No newline at end of file diff --git a/packages/nestjs-client/src/credentials/credential.service.ts b/packages/nestjs-client/src/credentials/credential.service.ts index 744ee33..e157499 100644 --- a/packages/nestjs-client/src/credentials/credential.service.ts +++ b/packages/nestjs-client/src/credentials/credential.service.ts @@ -307,7 +307,7 @@ export class CredentialService { credentialDefinitionId: string, maximumCredentialNumber: number = 1000, ): Promise { - const revocationDefinitionId = await this.apiClient.revocationRegistry.create({ + const revocationDefinitionId = await this.apiClient.revocationRegistries.create({ credentialDefinitionId, maximumCredentialNumber, })