js-libp2p
js-libp2p copied to clipboard
feat: add stream middleware
Adds middleware handlers for protocol streams. They are invoked for incoming and outgoing streams and allow access to the stream and connection before the handler (incoming) or caller (outgoing) receive them.
This way middleware can wrap streams in transforms, or deny access, or something else.
libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {
const originalSource = stream.source
// increment all byte values in the stream by one
stream.source = (async function * () {
for await (const buf of originalSource) {
buf = buf.map(val => val + 1)
yield buf
}
})()
// pass the stream on to the next middleware
next(stream, connection)
})
Change checklist
- [x] I have performed a self-review of my own code
- [x] I have made corresponding changes to the documentation if necessary (this includes comments as well)
- [x] I have added tests that prove my fix is effective or that my feature works
cc @dozyio
Amazing @achingbrain! thank you - Will have a play over the weekend