Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/francisrstokes/hexnut-client
https://github.com/francisrstokes/hexnut-client
Last synced: 14 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/francisrstokes/hexnut-client
- Owner: francisrstokes
- License: mit
- Created: 2019-02-23T15:37:01.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-01-04T10:31:39.000Z (almost 3 years ago)
- Last Synced: 2024-04-16T01:08:10.156Z (7 months ago)
- Language: JavaScript
- Size: 20.5 KB
- Stars: 9
- Watchers: 2
- Forks: 3
- Open Issues: 2
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
# Hexnut Client
`hexnut-client` is a middleware based websocket client designed to be used with Hexnut.
To get an idea about the core concepts of hexnut, check out the documentation page for hexnut server.
## Installation
```bash
npm i hexnut-client
```## Usage
### Creating a client
```javascript
const HexnutClient = require('hexnut-client');const client = new HexnutClient();
client.connect('ws://localhost:8080');
```### Using middleware
```javascript
const HexnutClient = require('hexnut-client');
const handle = require('hexnut-handle');const client = new HexnutClient();
client.use(handle.connect(ctx => {
ctx.send('Hello server!');
}));client.connect('ws://localhost:8080');
```## Recipes
### Using Hexnut Client with react
Using Hexnut with react is easily accomplished via the react context API.
```javascript
const HexnutClient = require('hexnut-client');
const React = require('react');
const reactDOM = require('react-dom');const client = new HexnutClient();
client.connect('ws://localhost:8080');const HexnutContext = React.createContext(client);
// ... Later
reactDOM.render(
document.getElementById('root'),
);
```### useHexnutMiddleware hook for react
This hook can be used when a react component (most likely a view) should control the middleware chain. It clears all the middleware and sets the chain provided to the hook.
```javascript
const useHexnutMiddleware = middlewareArray => {
const middlewareStr = middlewareArray.map(mw => mw.toString()).join('');
useEffect(() => {
client.middleware.splice();
middlewareArray.forEach(middleware => client.use(middleware));
}, [middlewareStr]);
};// Then, inside a function component
const MyComponent = props => {
const client = useContext(clientContext);
const [receivedMsg, setReceivedMsg] = useState(false);useHexnutMiddleware([
bodyparser.json(),
ctx => {
if (ctx.isMessage) {
setReceivedMsg(true);
if (ctx.message.type === 'showProps') {
ctx.send(JSON.stringify(props));
}
}
}
]);return receivedMsg
?We got a message
:Radio silence;
}
```