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

@devnetic/router

v2.0.0

Published

Simple router to match URLs.

Downloads

5

Readme

@devnetic/router

Node CI npm (scoped) npm bundle size (scoped) npm js-standard-style GitHub issues GitHub

Simple router to match URLs.

Usage

Using the router module in a HTTP server

const http = require('http')
const { router }  = require('@devnetic/router')

/**
 *
 * @param {IncomingMessage} request
 * @param {ServerResponse} response
 */
const requestHandler = (request, response) => {
  // Set a cookie in the response
  response.cookie('key', 'some-value')

  const data = {
    status: 'ok',
    body: request.body
  }

  response.header({
    'Content-Type': 'application/json',
    'X-Powered-By': 'kiirus-router'
  })

  // send JSON data easily
  response.json(data).end()
}

router.delete('/users', requestHandler)
router.get('/users', requestHandler)
router.patch('/users', requestHandler)
router.post('/users', requestHandler)
router.put('/users', requestHandler)

// attach method is the router handler to intercept every request to the server
// and validate if the request url is a valid defined route
const server = http.createServer(router.attach)

server.listen(3000, () => {
  console.log('listening in the port 3000')
})

Route Groups

const http = require('http')
const { router }  = require('@devnetic/router')

const requestHandler = (req, res) => {
}

const groupRoutes = [{
  method: 'post',
  path: 'login',
  requestHandler
}, {
  method: 'post',
  path: 'register',
  requestHandler
}]

router.group('v1', groupRoutes)

// attach method is the router handler to intercept every request to the server
// and validate if the request url is a valid defined route
const server = http.createServer(router.attach)

server.listen(3000, () => {
  console.log('listening in the port 3000')
})

Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), in the application’s request-response cycle.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
// Application level middleware
router.use((request, response) => {
  request.params = { ...request.params, ...{ foo: 'value' } }
  console.log('Application-level middleware')
})

// Route level middleware
router.use('/users', (request, response) => {
  console.log('Route-level middleware')
})

API Reference

request.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined.

const { router }  = require('@devnetic/router')

router.post('/users', (req, res) => {
  console.log(req.body)

  res.json(req.body)
})

request.cookies

When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

// Cookie: key=some-value
console.log(req.cookies.key)
// some-value

req.method

Contains a string corresponding to the HTTP method of the request: GET, POST, PUT, DELETE, etc.

req.params

This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /users/:id, then the "id" property is available as req.params.id. This object defaults to {}.

// GET /users/10
console.log(req.params.id)
// 10

req.query

This property is an object containing a property for each query string parameter in the route.

// GET /users?limit=10&offset=2
console.log(req.query)
// { limit: '10', offset: '2'}

req.route

Contains the currently-matched route, a string. For example:

royuter.get('/users/:id', (req, res) => {
console.log(req.route)
// {
//   handler: (request, response) => { … }
//   method: "GET"
//   params: Object {id: "10"}
//   path: /^\/users\/([A-Za-z0-9_-]+)$/ {lastIndex: 0}
//   query: Object {}
// }
})

router.clearCookie(name [, options])

Clears the cookie specified by name. For details about the options object, see res.cookie().

router.cookie('key', 'some-value', { path: '/dashboard' })
router.clearCookie('key', { path: '/dashboard' })

router.cookie(name, value [, options])

Sets cookie name to value. The value parameter may be a string or object converted to JSON.

The options parameter is an object that can have the following properties:

| Property | Type | Description | |----------|-------------------|---------------------------------------------------------------------------------------------| | domain | String | Domain name for the cookie. Defaults to the domain name of the app. | | expires | Date | Expire date of the cookie in GMT. If not specified or set to 0, creates a session cookie. | | httpOnly | Boolean | Flags the cookie to be accessible only by the web server. | | maxAge | Number | Convenient option for setting the expiry time relative to the current time in milliseconds. | | path | String | Path for the cookie. Defaults to “/”. | | secure | Boolean | Marks the cookie to be used with HTTPS only. | | sameSite | Boolean or String | Value of the “SameSite” Set-Cookie attribute. |

router.header(name ,value)

Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.

router.set('Content-Type', 'application/json')

router.set({
  'Content-Type': 'application/json',
  'X-Powered-By': 'kiirus-router'
})

router.json(body)

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

router.json(null)
router.json({ user: 'aagamezl' })
router.status(200).json({ status: 'ok' })

router.send(body)

Sends the HTTP response.

The body parameter can be a Buffer object, a String, an object, or an Array. For example:

res.send(Buffer.from('whoop'))
res.send({ some: 'json' })
res.send('<p>some html</p>')
res.status(404).send('Sorry, we cannot find that!')
res.status(500).send({ error: 'something blew up' })

router.status(code)

Sends the HTTP response.

Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

router.status(200).end()
router.status(400).send('Bad Request')
router.status(404).send('User not found')

Route Methods

  • DELETE: The DELETE method deletes the specified resource.
  • GET: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
  • HEAD: The HEAD method asks for a response identical to that of a GET request, but without the response body.
  • OPTIONS: The OPTIONS method is used to describe the communication options for the target resource.
  • PATCH: The PATCH method is used to apply partial modifications to a resource.
  • POST: The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
  • PUT: The PUT method replaces all current representations of the target resource with the request payload.

Changelog

Version 2.0.0

  • Auto verify routes.
  • Add middleware feature.
  • Remove verifyRoute() method.
  • Remove checkRoute() method.
  • Add body parsing.
  • Add form data parsing.
  • Add url encoded parsing.
  • Add cookie feature.
  • Improve code coverage.

Version 1.1.0

  • Deprecate verifyRoute() method.
  • Add new checkRoute() method to replace verifyMethod().
  • Add group method to assign multiples routes to a single group path.
  • Add documentation about available methods.

Version 1.0.0

  • Initial release

TODO

  • [X] Add more examples and usage description to README.
  • [X] Add group routes.
  • [X] Add more functionalities.
  • [X] Write missing test cases.
  • [X] Add code coverage.
  • [X] Migrate to TypeScript
  • [ ] Add more utility methods to request and response.