npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

rxserver

v0.6.0

Published

A node server using rxjs

Downloads

4

Readme

rxserver

This is a simple tiny http server for node. It uses a functional/reactive approach to be as simple as possible.

This server has the absolute minimal unique API, so that it is easy to use for beginners (i.e, without needing to learn a complex framework). While, advanced users can call on the full power of rxjs to adapt the system to their needs.

This also means that testing should be very easy, as the majority of your code should be simple functions that only include business logic.

This library was inspired by Building REST APIs with Observables and Node server with Rx and Cycle.js.

Installation

npm install --save rxserver

Getting started

Creating your first server is as easy as

const createServerCallbacks = require('rxserver').createServerCallbacks

const { httpServerCallback } = createServerCallbacks()

const hostname = '127.0.0.1'
const port = 1337

http.createServer(httpServerCallback)
  .listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`)
  })

Because we don't have any routes setup, a curl http://127.0.0.1:1337/ will respond with

{"error":"url not found"}

Adding middleware

All the magic lies in the middleware.

const { parse, tryCatch } = rxserver

const middleware = ({ http$ }) => ({
  http$: http$
    .do(logger)
    .catchMap(parse)
    .static(__dirname + '/public')
    .route(routes),
})

const { httpServerCallback } = createServerCallbacks(middleware)

The http$ is a RxJS Subject stream, i.e., an observable. It already has the operators map, switchMap and do attached.

The parse function asynchronously (hence the switchMap operator) converts { req, res } into { url, method, body, res }. It is wrapped in tryCatch

The switchCatch, route and static operators are unique to rxserver.

Operator: switchCatch

catchMap is the standard switchMap(predicate) changed to switchMap(tryCatch(predicate)). Where the tryCatch wraps your predicate function in a try/catch block, because Subject streams do not handle thrown errors well. I.e., .catchMap(parse) is equivalent to

switchMap(predicate => data => {
  try {
    return async predicate(data)
  } catch (e) {
    return ({ op: { error: e.message } })
  }
})

Operator: route

A route can be defined using simple functions, promises, async/await, or streams. E.g.,

const routes = [
  {
    url: '/name/:name',
    handler: ({ params }) => `Hello ${params.name}`,
  },
  {
    url: '/user',
    method: 'POST',
    handler: ({ body }) => Promise.resolve({ statusCode: 201, body }),
  },
  {
    url: '/search',
    handler: async function({ query }) {
      return await Promise.resolve({
        statusCode: 200,
        body: `async response: query = ${JSON.stringify(query)}`
      })
    },
  },
  {
    url: 'stream',
    handler: data => fs.createReadStream(__dirname + '/index.js'),  
  }
]

const middleware = ({ http$ }) => ({
  http$: http$
    .route(routes)
})

A route handler is supposed to be a simple function, e.g., see examples above. It can return a null, undefined, string, a promise, or an object of the shape

{
  statusCode: number || undefined,
  body: string || promise || object,
}

If you return a null or undefined, then req will continue to be checked against later routes. Whereas, if you respond with anything else, the request will not be checked against any further routes.

Examples can be found here

Operator: static [BETA]

Static servers the files from the directory passed to it:


const middleware = ({ http$ }) => ({
  http$: http$
    .route(routes)
})

TODO (pull requests welcome)

  • [ ] server side rendering
  • [ ] schema verification (optional)
  • [ ] authentication middleware
  • [ ] helmet security functionality
  • [ ] npm run example, etc *
  • [ ] tests: jest
  • [ ] circleci
  • [ ] websocket support
  • [ ] typescript && tsickle in example
  • [ ] business rules example
  • [ ] move to lerna, and split into multiple packages