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

blite

v1.3.4

Published

Lightweight batteries-included backend library.

Downloads

10

Readme

BLITE

Lightweight batteries-included backend library.

Overview

Blite is a monolithic backend server app that comes with built in services like user authentication, database, mail confirmation, etc. It is designed to be lightweight and fast prototyping for small to medium sized node.js projects. It is built on top of express and uses controldb as its database.

Features

  • Fast javascript document oriented database.
  • User registration and authentication.
  • Email confirmation and password reset.
  • File upload.
  • Demo app with user registration, login, profile, and file upload.

Installation

npm install blite

Usage

const blite = require('blite');

blite.start()
// server is now running on port 3000

Configuration

Blite can be configured by creating a blite.config.json file in the root directory of your project or by passing a configuration object to the init function. Following is the default configuration. This can be customized to suit your needs.

const config = {
    server:{
        port: 3000,
        jwt_private_key: "replace this something long and random"
    },
    auth: {
        cookie_name: "blite",
        access_token_life: "10800000",
        refresh_token_life: "7776000000"
    },
    email: {
        from: "",
        host: "",
        port: 0,
        username: "",
        password: ""
    },
    upload: {
        "max_file_size": 209715200,
        "dir": ""
    },
    db: {
        "name": "db",
        "collections": []
    }
}

blite.init(config).start()

Documentation

Demo app

Demo App

You can run demo app following way:

const blite = require('blite');

blite.demo()

Once you run the demo app, you can access it at http://localhost:3000. You can check out the demo app files in the demo folder. The demo app is a simple user registration, login, profile, and file upload app.

Server

Blite uses express as its server. You can check out the express documentation for more information here. Here are some of the most commonly used server functions.

Serving static files

Assume you have a folder named www in the root directory of your project and index.html file in it. You can serve it by following way:

// file structure
project
├── www
│   └── index.html
└── main.js
// main.js
const blite = require('blite');

blite.init()
blite.server.use("/", blite.server.static(`www`) )
blite.start()

Basic routing

The following examples illustrate defining simple routes.

const blite = require('blite');

blite.init()

// Respond with Hello World! on the homepage:
blite.server.get('/', (req, res) => {
  res.send('Hello World!')
})

// Respond to POST request on the root route (/), the application’s home page:
blite.server.post('/', (req, res) => {
  res.send('Got a POST request')
})

//Respond to a PUT request to the /user route:
blite.server.put('/user', (req, res) => {
  res.send('Got a PUT request at /user')
})

//Respond to a DELETE request to the /user route:
blite.server.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user')
})

blite.start()

For more details about routing, see the routing guide.

Middleware

Blite has built in middleware for authentication, registration, login, logout, password reset and file upload.

Registering middleware

You can register user by sending post request to your server from client side by providing username, email and password following way:

// client side
const data = {
    username: "username",
    email: "email",
    password: "password"
}
fetch("/api/register", {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
}).then((response) => {
    //...
}).catch(err => {
    //...
});

Then you need to define register route on server side and pass middleware to it following way:

// server side
blite.server.post("/api/register",
    blite.mid.register, // passing register middleware here
    async (req, res) => {
        if (res.error) {
            return res.status(400).json(res.error);
        }
        res.json({
            message: "You successfully registered."
        });
    });

Login middleware

You can login user by sending post request to your server from client side by providing username, password and rememberMe flag following way:

// client side
const data = {
    username: "username",
    password: "password",
    rememberMe: true
}
fetch("api/login", {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
}).then((response) => {
    //...
}).catch(err => {
    //...
});

Then you need to define login route on server side and pass middleware to it following way:

// server side
blite.server.post("/api/login",
    blite.mid.login, // passing login middleware here
    async (req, res) => {
        if (res.error) {
            return res.status(400).json(res.error);
        }
        res.json({
            message: "You successfully logged in."
        });
    });

Logout middleware

You can logout user by sending post request to your server from client side. No data is required. Once you send request, the access token and refresh token will be deleted from the database.

// client side
fetch("api/logout", {method: 'POST'})

Then you need to define logout route on server side and pass middleware to it following way:

// server side
blite.server.post("/api/logout",
    blite.mid.logout, // passing logout middleware here
    async (req, res) => {
        // ...
    });

Authentication middleware

You don't want your user to login every time they visit your app. You can use authentication middleware to check if the user is already logged in or not. If the user is logged in blite will store access and refresh token. When you send use authentication middleware, blite will check if the access token is valid or not. You can give access to the user if the access token is valid by sending post request to your server from client side following way:

fetch("/api/authenticateSession", { 
    method: 'POST' 
}).then((response) => {
    // Give access to the user
}).catch(err => {
    // Redirect to login page
});

Then you need to define authenticateSession route on server side and pass middleware to it following way:

blite.server.post("/api/authenticateSession",
    blite.mid.authenticateSession, // passing authenticateSession middleware here
    async (req, res) => {
        // Now you can start making authenticated requests from client side
    });

Once session is authenticated, you can allow user to access protected routes by using authenticeUser middleware following way:

router.post("/api/userInfo",
    blite.mid.authenticateUser, // passing authenticateUser middleware here
    async (req, res) => {
        if (res.error) {
            return res.status(400).json(res.error);
        }
        res.json({
            user: req.user,
            message: "success"
        });
    });

Upload middleware

You can upload files by using form data and sending post request to your server from client side following way:

fetch("/api/upload", {
    method: 'POST',
    body: formData
})

Then you need to define upload route on server side and pass middleware to it following way:

// server side
router.post("/api/upload",
    blite.mid.decodeUpload, // passing decodeUpload middleware here
    async (req, res) => {
        if (res.error) {
            return res.status(400).json(res.error);
        }

        const uploadedFile = req.files.upload.filepath;
        // Do something with the file

        res.json({
            message: "File successfully uploaded."
        });
    });

Database

Blite uses ControlDB as its database. Its a simple and fast document based database that stores data in JSON files. You can check out ControlDB here for more details. Here are some examples of how you can use ControlDB with Blite.

Creating a database

You can create a database by passing config object with database parameters. As default, Blite will create an empty database named "blite". Its also possible to create a database with some collections by passing options such as collection name, indices and unique fields etc.

const config = {
    ...,
    db: {
        name: "myDatabase",
        collections: [{ // You can either create collections here or you can create them later on
            name: "users",
            options: {
                indices: [
                    "username"
                ],
                unique: [
                    "username",
                    "email"
                ]
            }
        },
        {
            name: "posts",
            options: {...}
        }]
    }
};

blite.init(config).start()

Add a collection :

var users = blite.db.addCollection('users');

Insert documents :

users.insert({
	name: 'Odin',
	age: 50,
	address: 'Asgard'
});

// alternatively, insert array of documents
users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]);

Simple find query :

var results = users.find({ age: {'$gte': 35} });

var odin = users.findOne({ name:'Odin' });

Simple where query :

var results = users.where(function(obj) {
	return (obj.age >= 35);
});

Simple Chaining :

var results = users.find({ age: {'$gte': 35} }).simplesort('name').docs();

Simple named transform :

users.addTransform('progeny', [
  {
    type: 'find',
    value: {
      'age': {'$lte': 40}
    }
  }
]);

var results = users.chain('progeny').docs();

Simple Dynamic View :

var pview = users.addDynamicView('progeny');

pview.applyFind({
	'age': {'$lte': 40}
});

pview.applySimpleSort('name');

var results = pview.docs();

For more details, check out ControlDB documentation here

Conclusion

Blite is a simple and fast framework that allows you to create a full stack web application in minutes. It has a lot of features that you can use to build your next project. If you have any questions or suggestions, feel free to contact me. I hope you enjoy using Blite.

License

MIT License