Skip to content

newalvaro9/hyper-routing

Repository files navigation

Hyper-Routing

version license downloads

An amazing and simple route manager

Instalation

npm i hyper-routing

Table of contents

Usage

// Using Node.js `require()`
const hyperRouting = require('hyper-routing');

// Using ES6 imports
import hyperRouting from 'hyper-routing';

const app = new hyperRouting()

Application instance

<method>(path, ...callbacks)

Argument Description
method The method to be handled in the url.
To put one of the listed below:
get, post, delete, put, patch
path A string representing the url to handle.
...callbacks A middleware function or a series of middleware functions separated by commas.
Must have a next() function in the middleware to pass control to the next middleware.
app.get('/', (req, res, next) => {
    // Do something
});

app.post('/', (req, res, next) => {
    // Do something
});

use(middleware)

Uses a middleware function in all routes.

Argument Description
middleware A function that executes some code, modifies the req or res object, ends the req-res cycle or calls the next middleware function with the next() function.
If the middleware function doesn't end the req-res cycleit must call next() to pass control to the next middleware function.
/* Creating own middleware */
const myOwnMiddleware = (req, res, next) => {
    console.log("Hello world!") 
    console.log(`I was called on ${req.url}`)
    next(); // Important to pass control to next middleware function
}

app.use(myOwnMiddleware)

listen(port, callback)

Starts the server in the desired port.

Argument Description
port A number representing the port to be used to alocate the webpage on.
http://localhost:port/
callback What to do when the webpage is ready.
app.listen(3000, () => {
    // Do something
});

Middlewares

bodyparser({...parser})

Parses the req data into object readable data.

Argument Description
...parsers Parsers can be the ones listed below seted to true or false:
json, urlencoded
Those are set by default to true if no ...parsers are specified and if only one parser is specified the default see example below.
app.use(app.bodyparser()) // Will parse both application/json and www-x-form-urlencoded data
app.use(app.bodyparser({ json: true })) // Will only parse application-json data
app.use(app.bodyparser({ urlencoded: true })) // Will only parse www-x-form-urlencoded data

Request

body

Attribute of the Request class containing the <input/> values of the <form/> with key based in their names attribute.

<form action="/login">
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit">Login</button>
</form>
{
    username: "someusername",
    password: "somepassword"
}
app.post('/login', (req, res) => {
    const { username, password } = req.body;
});

params

Attribute of the Request class with the specified parameters in the path.

// http://localhost:3000/users/12345
{
    id: "123458"
}
// http://localhost:3000/users/12345
app.get('/users/:id', (req, res) => {
    const { id } = req.params;
    console.log(id); // Logs 123458
});

query

Attribute of the Request class with the query parameters in the url.

// http://localhost:3000/products?category=clothes&design=fancy&sort=recent
{
    category: "clothes",
    design: "fancy",
    sort: "recent"
}
// http://localhost:3000/products?category=clothes&design=fancy&sort=recent
app.get('/products', (req, res) => {
    const { category, design, sort } = req.query;
    console.log(category); // Logs clothes
    console.log(design); // Logs fancy
    console.log(sort); // Logs recent
});

Response

status(code)

Sets the response status code.

Argument Description
code A number or a literal string representing the status code to be sent.
app.get('/', (req, res) => {
    res.status(404) // Status Code: 404
    res.status("Not Found") // Status Code: 404
});

json(data)

Sends an application/json content-type response.

Argument Description
data The object that will be sent.
app.get('/', (req, res) => {
    res.json({
        username: "Álvaro",
        age: "16"
    }) // Will display a JSON object
});

send(data)

Sends a text/plain content-type response.

Argument Description
data Any type of data to be sent.
app.get('/', (req, res) => {
    res.send("An amazing webpage :)")
});

app.get('/', (req, res) => {
    res.send({ // As this is an object it will trigger res.json()
        data: "An amazing webpage :)" 
    })
});

sendFile(path)

Sends a text/html content-type response.

Argument Description
path The path inside views folder were the .html file is.
app.get('/', (req, res) => {
    res.sendFile("index.html")
});

redirect(url)

Redirects to the specified url.

Argument Description
url A string representing the new url path.
app.get('/profile', (req, res) => {
    if(!req.user) { // Using some type of auth
        res.redirect('/login'); // Redirects the user to http://localhost:3000/login
    };
});

Examples

Check out the examples to see how you can use hyper-routing in a project.

Help

Have any doubts or suggestions?
Send me a private message on Discord: @newalvaro9

License

MIT

Copyright 2023, Álvaro Poblador.
Inspired in express.js