Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
boytur committed Nov 11, 2024
0 parents commit b9be5ae
Show file tree
Hide file tree
Showing 6 changed files with 611 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 BSO Space

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
81 changes: 81 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@

# WebSocket Client CLI for Microservice Interaction

This project contains a CLI application that interacts with a WebSocket server and sends login notifications to a microservice when the `user.login` event is received. It is designed to be used in development environments where WebSocket messages are received and then sent to a microservice via a webhook on `localhost`.

## Features

- **WebSocket connection**: Connects to a WebSocket server and sends a connection message with a token and microservice URL.
- **Event handling**: Handles `user.login` events from the WebSocket server and sends the data to a specified microservice URL.
- **Webhook integration**: The application sends a POST request to a microservice using a webhook URL on `localhost`, making it ideal for local development and testing.
- **Logging**: Logs messages with timestamps for better tracking and troubleshooting.

## Requirements

- Node.js (>= v14)
- WebSocket server running at a specified URL (local or remote)
- A microservice capable of handling `user.login` events at the provided URL (typically a local server, e.g., `http://localhost:3001/open/hook`)
- `node-fetch` for sending HTTP requests

## Installation

1. Clone the repository:

```bash
git clone https://github.com/BSO-Space/socketlink.git
cd websocket-client-cli
```

2. Install dependencies:

```bash
npm install
```

## Usage

You can use the CLI tool to connect to the WebSocket server and interact with the microservice.

### Command Line Arguments

- `--url` or `-u`: WebSocket server URL (e.g., `ws://localhost:3005` or `ws://example.com`)
- `--microservice-url` or `-m`: Microservice URL to send the login data to (e.g., `http://localhost:3001/open/hook`), ideal for local testing environments.
- `--token` or `-t`: Authentication token to send with the microservice URL.

### Example

```bash
node cli.js --url ws://localhost:3005 --microservice-url "http://localhost:3001/open/hook" --token "cm3bwtymf0000qj6vr8ykrdku"
```

### Expected Output

1. **Connection message**: The client connects to the WebSocket server and sends the token and microservice URL.
- Example:
```bash
[2024-11-11T11:42:30.666Z] [INFO] Connected to WebSocket server at ws://localhost:3005
[2024-11-11T11:42:30.668Z] [INFO] Sending connection message with token and microservice URL
```

2. **Received message**: Any general WebSocket messages will be logged, except for the `user.login` events.
- Example:
```bash
[2024-11-11T11:42:30.935Z] [INFO] General WebSocket Message: Hello World, blog 🎉👋
[2024-11-11T11:42:30.935Z] [ERROR] Incoming message is not valid JSON: Hello World, blog 🎉👋
```

3. **Handling `user.login` event**: When a `user.login` event is received, it sends the data to the microservice.
- Example:
```bash
[2024-11-11T11:42:45.573Z] [INFO] Handling 'user.login' event from WebSocket server
```

### Local Development Use Case

This CLI tool is ideal for **local development** when you're testing WebSocket interactions and need to send data to your locally running microservice (e.g., on `http://localhost:3001`). The tool listens for `user.login` events on the WebSocket server and forwards this data directly to your microservice via a webhook.
This setup is helpful when you are developing and testing your microservice and need to simulate the interaction with the WebSocket server in a local environment.
### License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
164 changes: 164 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
#!/usr/bin/env node

import WebSocket from "ws";
import yargs from "yargs";
import fetch from "node-fetch";
import figlet from "figlet";
import chalk from "chalk";

console.log(
chalk.green(
figlet.textSync("BSO CLI", {
horizontalLayout: "full",
verticalLayout: "default",
width: 80,
whitespaceBreak: true,
})
)
);
console.log(chalk.yellow("Socketlink is running...\n"));

// CLI arguments
const argv = yargs(process.argv.slice(2))
.command(
"start",
"Start the WebSocket connection and interact with the microservice",
(yargs) => {
return yargs
.option("url", {
alias: "u",
type: "string",
demandOption: true,
description: "WebSocket server URL, e.g., ws://localhost:3001",
})
.option("microservice-url", {
alias: "m",
type: "string",
demandOption: true,
description:
"Local URL of the microservice, e.g., http://localhost:5000",
})
.option("token", {
alias: "t",
type: "string",
demandOption: true,
description: "Authentication token to send with the microservice URL",
});
},
async (argv) => {
await startWebSocket(argv.url, argv.microserviceUrl, argv.token);
}
)
.help()
.alias("help", "h").argv;

// Function to get the current time in ISO format
function getCurrentTime() {
return new Date().toISOString();
}

// Function to start the WebSocket connection
async function startWebSocket(url, microserviceUrl, token) {
const ws = new WebSocket(url);

ws.on("open", () => {
console.log(
`[${getCurrentTime()}] [INFO] Connected to WebSocket server at ${url}`
);

const message = {
token: token,
microserviceUrl: microserviceUrl,
};

console.log(
`[${getCurrentTime()}] [INFO] Sending connection message with token and microservice URL`
);
ws.send(JSON.stringify(message));
});

// Handle incoming WebSocket messages
ws.on("message", async (data) => {
const message = data.toString();

if (message.includes("user.login")) {
console.log(
`[${getCurrentTime()}] [INFO] Handling 'user.login' event from WebSocket server`
);
}

if (!message.includes("user.login")) {
console.log(
`[${getCurrentTime()}] [INFO] General WebSocket Message: ${message}`
);
}

if (isJsonString(message)) {
try {
const result = JSON.parse(message);

if (result.event === "user.login") {
console.log(
`[${getCurrentTime()}] [INFO] Handling 'user.login' event`
);

// Send data to microservice
const res = await fetch(microserviceUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-hook-token": result.token,
"x-hook-signature": result.signature,
},
body: JSON.stringify(result.payload),
});

const resData = await res.json();

if (res.ok) {
console.log(
`[${getCurrentTime()}] [INFO] Data sent to microservice successfully`
);
} else {
console.error(
`[${getCurrentTime()}] [ERROR] Error sending data to microservice:`,
resData
);
}
}
} catch (error) {
console.error(
`[${getCurrentTime()}] [ERROR] Failed to parse incoming message or handle event:`,
error.message
);
}
} else {
console.error(
`[${getCurrentTime()}] [ERROR] Incoming message is not valid JSON:`,
message
);
}
});

// Handle WebSocket errors
ws.on("error", (error) => {
console.error(
`[${getCurrentTime()}] [ERROR] WebSocket error: ${error.message}`
);
});

// Handle WebSocket close event
ws.on("close", () => {
console.log(`[${getCurrentTime()}] [INFO] WebSocket connection closed`);
});
}

// Utility function to check if a string is valid JSON
function isJsonString(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
Loading

0 comments on commit b9be5ae

Please sign in to comment.