1.0.3 • Published 7 months ago

backend-made-easy v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

Project Title : Backend-Made-Easy

A simple and powerful npm package for backend developers, designed to make building backends easy and efficient.

Introduction

This npm package is designed for beginner backend developers who want to create scalable and maintainable backend systems without diving into complex configurations.

With this package, you can:

Set up a server in seconds. Use pre-configured database integration. Access reusable middleware and utilities for authentication, error handling, and more.

Getting Started

To get started with Easy-Backend-Starter, follow these simple steps:

  1. Set up your development environment
  2. Install the package
  3. Create your first server
  4. Start building your backend!

Prerequisites

Before installing Easy-Backend-Starter, make sure you have the following:

  • Node.js : Version 14.x or higher
  • npm : Version 6.x or higher
  • MongoDB : Version 4.x or higher (if using database features)
  • Git : Latest version recommended
  • Code Editor : VS Code, Sublime Text, or any preferred editor

Installing

Install the package using npm:

npm i easy-backend-starter

Usage

// Importing the EasyBackend class from the 'backend-made-easy' package
// This class is designed to simplify the setup of an Express.js server.
const { EasyBackend } = require("backend-made-easy");

// Creating an instance of EasyBackend with custom configuration
// The configuration object allows you to define the following:
// - `port`: The port on which the server will run (default: 3000).
// - `corsOrigin`: The allowed origin for Cross-Origin Resource Sharing (CORS) (default: '*').
const app = new EasyBackend({
  port: 5000, // The server will run on port 5000.
  corsOrigin: "*", // Allow all origins to access the server (useful during development).
});

// Accessing the underlying Express.js instance through the `initialize()` method
// This is optional and should be used only if you need to:
// - Add custom middleware
// - Define additional routes
// - Integrate third-party libraries
// NOTE: If you don't need to customize the app, you can skip this step.
const test = app.initialize();

test.use((req, res, next) => {
  console.log("Middleware executed");
  next();
});

// Starting the server using the `start()` method
// This method begins listening on the specified port (5000 in this case)
// and logs a message to indicate the server has started successfully.
// Always call `start()` after configuring your server.
app.start();

// creating routes in route.js file and importing it in main file
/**
 * Importing the `CreateRoutes` class from your package.
 * This class helps simplify route creation in Express.js applications.
 */
const { CreateRoutes } = require("backend-made-easy");

/**
 * Step 1: Initialize the `CreateRoutes` class.
 * This creates an instance of the route manager to define and manage your routes.
 */
const createRoutes = new CreateRoutes();

/**
 * Step 2: Define a simple GET route.
 *
 * - `path`: The endpoint for the route.
 * - `handler`: The function that will handle requests to this endpoint.
 * - `middleware`: (Optional) Array of middleware functions to be executed before the handler.
 * - `successMessage`: (Optional) Custom message to be sent on a successful response.
 * - `successCode`: (Optional) HTTP status code for a successful response (default is 200).
 */
createRoutes.get({
  path: "/test/hello", // The URL path for this endpoint.
  handler: async (req, res) => {},
  successMessage: "Greeting fetched successfully", // Custom success message
  successCode: 200, // HTTP 200 OK
});

/**
 * Step 2: Define a GET route with pagination.
 * This route demonstrates how to handle paginated responses for fetching a list of users.
 */
createRoutes.get({
  path: "/test/users", // Endpoint to fetch a paginated list of users.
  handler: async (req, res) => {
    // Extracting pagination parameters from the query string.
    const { page = 1, limit = 10 } = req.query;

    // Simulating a database of users (in a real-world app, this would come from a database query).
    const allUsers = Array.from({ length: 100 }, (_, i) => ({
      id: i + 1,
      name: `User${i + 1}`,
      email: `user${i + 1}@example.com`,
    }));

    // Calculating pagination boundaries.
    const startIndex = (page - 1) * limit; // Start index for the current page.
    const endIndex = page * limit; // End index for the current page.

    // Slicing the users array to return only the users for the requested page.
    const paginatedUsers = allUsers.slice(startIndex, endIndex);

    // Preparing the paginated response.
    const response = {
      success: true,
      message: "Users fetched successfully",
      data: paginatedUsers,
      meta: {
        total: allUsers.length, // Total number of users.
        page: parseInt(page, 10), // Current page number.
        limit: parseInt(limit, 10), // Number of users per page.
      },
    };

    // Returning the paginated response.
    return response;
  },
  successMessage: "Users fetched successfully", // Custom success message.
  successCode: 200, // HTTP 200 OK status code.
});

/**
 * Step 4: Define a POST route with middleware.
 * Middleware is executed before the handler function.
 */
createRoutes.post({
  path: "/test/user", // The URL path for this endpoint.
  middleware: [
    (req, res, next) => {
      console.log("Middleware executed before handler!");
      next(); // Call `next()` to proceed to the handler.
    },
  ],
  handler: async (req, res) => {
    const { name, age } = req.body;
    // Business logic for the POST request
    return { name, age, id: Math.random().toString(36).substring(7) };
  },
  successMessage: "User created successfully", // Custom success message
  successCode: 201, // HTTP 201 Created
});

/**
 * Step 5: Define a DELETE route.
 * DELETE routes are typically used to remove resources.
 */
createRoutes.delete({
  path: "/test/user/:id", // The URL path with a dynamic parameter `id`.
  handler: async (req, res) => {
    const { id } = req.params;
    // Business logic for deleting the user with the specified ID
    return { id };
  },
  successMessage: "User deleted successfully", // Custom success message
  successCode: 204, // HTTP 204 No Content
});

/**
 * Step 6: Export the router.
 * The `useRouter` method returns an Express Router instance.
 * This can be attached to your main Express application.
 */
module.exports = createRoutes.useRouter();


const testRoute = require("./route");
test.use("/api", testRoute);

License

MIT

1.0.3

7 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago