• Stars
    star
    208
  • Rank 189,015 (Top 4 %)
  • Language
    JavaScript
  • Created almost 6 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ”© Hexnut is a middleware based, express/koa like framework for web sockets

Hexnut

Hexnut is a middleware based, express/koa like framework for web sockets.

npm version license CircleCI

For an introduction, and API documentation, please check out the docs.

Middleware

Client side

You can use hexnut as a client in the frontend with hexnut-client. It is also middleware based and can use many of the server middlewares directly, such as hexnut-bodyparser and hexnut-sequence.

Examples

Trivial Example

const Hexnut = require('hexnut');
const errorService = require(/* some error logging service */);
const app = new Hexnut({ port: 8080 });

app.onerror = async (err, ctx) => {
  await errorService(err);
  ctx.send(`Error! ${err.message}`);
};

app.use(ctx => {
  if (ctx.isConnection) {
    ctx.state = { count: 0 };
    return ctx.send('Hello, and welcome to the socket!');
  }

  ctx.state.count++;
  ctx.send(`Message No. ${ctx.state.count}: ${ctx.message}`);
});

app.start();

Parsing JSON automatically

const Hexnut = require('hexnut');
const bodyParser = require('hexnut-bodyparser');
const app = new Hexnut({ port: 8080 });

app.use(bodyParser.json());

app.use(ctx => {
  if (ctx.isConnection) {
    ctx.state = { count: 0 };
    return ctx.send('Hello, and welcome to the socket!');
  }

  if (ctx.message.type) {
    ctx.state.count++;
    ctx.send(`Message No. ${ctx.state.count}: ${ctx.message.type}`);
  } else {
    ctx.send(`Invalid message format, expecting JSON with a "type" key`);
  }
});

app.start();

Handling messages by type

const Hexnut = require('hexnut');
const handle = require('hexnut-handle');
const app = new Hexnut({ port: 8080 });

app.use(handle.connect(ctx => {
  ctx.count = 0;
}));

app.use(handle.matchMessage(
  msg => msg === 'incCount',
  ctx => ctx.count++
));

app.use(handle.matchMessage(
  msg => msg === 'decCount',
  ctx => ctx.count--
));

app.use(handle.matchMessage(
  msg => msg === 'getCount',
  ctx => ctx.send(ctx.count)
));

app.start();

Sequencing Interactions

const Hexnut = require('hexnut');
const bodyParser = require('hexnut-bodyparser');
const sequence = require('hexnut-sequence');
const app = new Hexnut({ port: 8080 });

app.use(bodyParser.json());

// This sequence happens when the user connects
app.use(sequence.onConnect(function* (ctx) {
  ctx.send(`Welcome, ${ctx.ip}`);
  const name = yield sequence.getMessage();
  ctx.clientName = name;
  return;
}));

app.use(sequence.interruptible(function* (ctx) {
  // In order to use this sequence, we assert that we must have a clientName on the ctx
  yield sequence.assert(() => 'clientName' in ctx);

  // We first expect a message with type == greeting
  const greeting = yield sequence.matchMessage(msg => msg.type === 'greeting');

  // Then a message that has type == timeOfDay
  const timeOfDay = yield sequence.matchMessage(msg => msg.type === 'timeOfDay');

  return ctx
    .send(`And a ${greeting.value} to you too, ${ctx.clientName} on this fine ${timeOfDay.value}`);
}));

app.start();

Integrating with rxjs

const Hexnut = require('hexnut');
const { withObservable, filterMessages } = require('hexnut-with-observable');

const { tap, filter } = require('rxjs/operators');
const { pipe } = require('rxjs');

const app = new Hexnut({ port: 8181 });

app.use(withObservable(pipe(
  // Do setup operations here...
  tap(({ctx}) => {
    if (ctx.isConnection) {
      console.log(`[${ctx.ip}] Connection started`);
    }
  }),

  // Filter to only messages
  filterMessages(msg => msg !== 'skip'),

  // Process messages
  tap(({ctx, next}) => {
    ctx.send(`You sent: ${ctx.message}`);
  })
)));


app.start();

More Repositories

1

super-expressive

🦜 Super Expressive is a zero-dependency JavaScript library for building regular expressions in (almost) natural language
JavaScript
4,464
star
2

construct-js

πŸ› οΈA library for creating byte level data structures.
TypeScript
1,349
star
3

arcsecond

✨Zero Dependency Parser Combinator Library for JS Based on Haskell's Parsec
TypeScript
500
star
4

16bitjs

πŸ’» A 16-bit virtual machine, including assembly language with 37 instructions, binary assembler, and a step through debugger
JavaScript
470
star
5

githublog

I'm sick of complex blogging solutions, so markdown files in a git repo it is
338
star
6

tega

πŸ•Ή TypeScript Embedded GameBoy Macro Assembler
TypeScript
227
star
7

React-Machinery

πŸ”₯ React Machinery provides a simple to use, component based approach to state machines in react.
JavaScript
105
star
8

vec-la

Tiny linear algebra library specifically for 2d
JavaScript
41
star
9

bewitched

πŸ§™πŸ» Command line hex editor
TypeScript
35
star
10

Lazy-Infinite-List

πŸ—’οΈ A Fantasy Land compliant Infinite List Data Structure
JavaScript
26
star
11

tiny-c-projects

A collection of small C projects - usually a minimal example of something interesting
C
25
star
12

vmfc

Stack-based VM Architecture in JavaScript. (Virtual Machine Fantasy Console)
JavaScript
23
star
13

vec-la-fp

↗️ A tiny (functional) 2d linear algebra library
JavaScript
22
star
14

arcsecond-binary

Binary parsers for arcsecond!
JavaScript
19
star
15

GMMK-Driver

An open source, reverse engineered control driver for the GMMK mechanical keyboard
TypeScript
19
star
16

AES-C

A (non-production) implementation of AES for educational purposes
C
14
star
17

teensy-nes

NES Emulator on a Teensy 4.1
C++
8
star
18

hexnut-client

JavaScript
8
star
19

trump-chain

JavaScript
8
star
20

kandinsky-js

🌈A tiny colour library
JavaScript
7
star
21

Classiest

🍸 Create classier classes with overloadable methods, getters, setters, and statics!
JavaScript
7
star
22

ebpf-usb

A tool for monitoring (specific) USB devices
Python
6
star
23

super-expressive-fp

SuperExpressive, but with a wrapped API for functional programming
JavaScript
6
star
24

Image-Glitcher

πŸ’’ Generates glitchy GIFs from JPEGs
JavaScript
5
star
25

rustack-machine

A simple stack machine in rust
Rust
5
star
26

bito

B.I.T.O - Programatic Beats Code Golfed In Your Browser
JavaScript
5
star
27

Steganography-C

Steganographic encoding implementation for hiding data in images
C
4
star
28

ATmega328P-Bare-Metal-Task-Switching

πŸŽ– A minimal implementation of a task-switching kernel in C for the ATmega328P chip
C
4
star
29

hexnut-sequence

Sequencing middleware for the HexNut framework
JavaScript
3
star
30

hexnut-handle

Simple hexnut middleware for dealing with connections and messages
JavaScript
3
star
31

algebraic-types

JavaScript
3
star
32

SpelBoy

A GameBoy (DMG) emulator written in TypeScript
TypeScript
3
star
33

modular-animation-synthesizer

https://francisrstokes.github.io/modular-animation-synthesizer/
JavaScript
3
star
34

frame-http

πŸ–ΌοΈLaughably minimal http framework combining the best parts of express and koa
JavaScript
3
star
35

ElessarOS

risc-v OS inspired by xv6
C
2
star
36

Brainfuck-Interpreter

Brainfuck interpreter using Jison
JavaScript
2
star
37

SNES-Controller-Arduino-Leonardo

Turn the SNES controller into a USB controller for use with an emulator
C++
2
star
38

zig-expressions

A regular expression engine written in Zig
Zig
2
star
39

lazy-do

Fantasy Land compliant do notation for lazy structures πŸ¦„
JavaScript
2
star
40

readme-cli

πŸ“– A CLI tool for rendering npm/github README files in the terminal
JavaScript
2
star
41

microcan

JavaScript
2
star
42

simple-transduce

A really simple transducer module to easily convert map-filter-reduce chains to single pass transducers.
JavaScript
2
star
43

creative-code-toolkit-fp

JavaScript
2
star
44

aoc-2023

Zig
1
star
45

WaveStrider

CMake
1
star
46

lambda-lang

JavaScript
1
star
47

hexnut-bodyparser

JavaScript
1
star
48

hexnut-restore-connection

HexNut middleware to restore a lost connection
JavaScript
1
star
49

app-and-bootloader

Simple app and bootloader implementation for STM32 using libopencm3
Makefile
1
star
50

salsa20-on-rp2040

My entry for LLJam0001: Salsa20 hardware encryption device using a Raspberry Pi Pico
C
1
star
51

microcan-fp

JavaScript
1
star
52

riscv-gateware-ts

A RISC-V processor with gateware-ts
TypeScript
1
star
53

bus-pirate

Bus Pirate integration for TS and JS
TypeScript
1
star
54

primer-js

πŸ•° A tiny (474 bytes minified + gzipped) library for creating normalised, unit independent timelines
JavaScript
1
star
55

zig-stm32-bare-metal

Minimal zig code to blink a LED for the STM32F401RE chip
Zig
1
star
56

Jazz-Chordr

Memorise common jazz chords https://francisrstokes.github.io/Jazz-Chordr/
JavaScript
1
star
57

Hindley-Milner-Parser

A Hindley-Milner type signature parser in haskell
Haskell
1
star
58

hexnut-with-observable

A Hexnut middleware for integrating with rxjs
JavaScript
1
star
59

Redux-State-Resolver

πŸ’‘Cleanly resolve a sequence of dependencies - write component logic that can assume the state has what it needs.
JavaScript
1
star
60

x86_64-Userspace-Emulator

C
1
star
61

hexnut-router

Routing middleware for HexNut
JavaScript
1
star
62

c-proj-init

A script to generate a skeleton C project, with a minimal Makefile and vscode debugging
JavaScript
1
star
63

autonotyper

An automatic typing engine tht can be plugged into anything
JavaScript
1
star
64

4FVM

Spiritual successor to 16bitJS
JavaScript
1
star
65

gibson-engine

A minimalist text game (interactive fiction) engine
JavaScript
1
star