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

@xernois/easy-backend

v0.0.10

Published

This project is a basic nodejs "framework" to ease the creation of advanced api's, based directly on the nodejs http server. I am working on this project alone and in my spare time, but if you are interested in this project don't hesitate to contact me or

Downloads

22

Readme

Easy backend

This project is a basic nodejs "framework" to ease the creation of advanced api's, based directly on the nodejs http server. I am working on this project alone and in my spare time, but if you are interested in this project don't hesitate to contact me or create a pull request 😉.

Features

  • Server
  • controller/route
  • resolvers
  • services
  • middlewares

🖥️ Server

Servers are simply instances, so you can easily create a server and configure it to use the correct source files.

import app from "@xernois/easy-backend";

const server = app({
  appFolder: "src", // the folder containing controllers, middlewares and services
});

server.listen(3000, () => {
  // 3000 being an arbitrary port you can change to any port yo want o user
  console.log("Server started on port 3000"); // this message will be logged once the server is listening on port 3000
});

PS: This means that you can easily create multiple server instances listening on different ports.

🧭 controller/route

Controllers are classes that contain one or more routes and can have a default path that affects all of it's routes.

import { Controller, Method, Response, Request, Route } from '@xernois/easy-backend';
import UserResolver from '../resolvers/UserResolver';

@Controller({ path: '/main' }) // default path for every route /main
export default class MainController {

  // a route matching GET /main/user/*
  @Route({ path: '/user/:user', method: [Method.GET], name: 'dynamic', resolvers: { 'user': UserResolver } })
  public dynamic(req: Request, res: Response) {

    res.end(req.data?.['user']) // send back the user data to the client

  }
}

Above is an example of a simple controller, but with a default path of /main (this is optional). This controller has only one route, a route is defined by a path, a list of methods, a name and a handler. In the example the path /user/:user means that it will match any url like /main/user/test, /main/user/123 or /main/user/1_b_r and that the variable part of the url will be accessible via a variable of the same name in the request params object req.params?.['user']. The handler takes two arguments, the request and the response, these are just the normal nodejs objects but slightly extended, see the nodejs doc.

The last thing you may have noticed is the resolver, the resolver is used to resolve data as the route is accessed, in the example above when accessing the url /main/user/1 it will get datas for the user with id one and give access to this data inside the handler. The user data can be found under the req.data?.['user'] object.

PS: Note that the resoler key must be the same as the variable in the path.

🔎 Resolvers

A resolver is a class that implements the IResolver interface and therefore the resolve method, which takes the url variable as a parameter and returns modified data.

import { Resolver, IResolver } from "@xernois/easy-backend";
import MainService from "../services/mainService";

@Resolver({singleton: false})
// singleton parameter otional, but it only mean that an instance will be created for each access attemp on any of the routes using this resolver
export default class UserResolver implements IResolver<string> {

    constructor(
        private mainService: MainService // injecting the service that contains our data
    ) { }

    resolve(userID?: string): string { // Signature may vary but the method is mandatory on a resolver.
        // return the users data
        return this.mainService.getUserByID(userID);
    }
}

Resolvers are not meant to hold data, just to access it and make it easier to use controllers. However, you can avoid resolvers altogether and inject a service into your controller to access all your data directly from the route handler.

🗃️ services

Services are objects designed to access/manipulate data from a database or other data source.

import { Injectable } from "@xernois/easy-backend";

@Injectable()
export default class dataService {
  constructor() {}

  data: number[] = [];

  getAndAdd() {
    this.data.push(Math.random()); // add a random number to the array

    return this.data; // return the random number and all random number that were previusly generated by other getAndAdd calls
  }
}

there is nothing really specific to services except that these are singletons. this mean that everytime you use the dataService (just an example) it will always be the same instance. That's why storing the array directly on the service is working.

🛡️ Middlewares

Middleware is only used to modify or block requests before they reach the handler, it can be used for authentication, for example to restrict access to certain routes. It can be applied to a specific route or directly to a controller.

import { Controller, Method, Response, Request, Route } from '@xernois/easy-backend';
import UserResolver from '../resolvers/UserResolver';
import LoggerMiddleware from '../middlewares/loggerMiddleware';

@Controller({ path: '/main', middlewares: [LoggerMiddleware] })
export default class MainController {

  @Route({ path: '/user/:user', method: [Method.GET], name: 'dynamic', resolvers: { 'user': UserResolver } })
  public dynamic(req: Request, res: Response) {

    res.end(req.data?.['user'])

  }
}

In this example, the LoggerMiddleware is applied to the controller, which means that it will affect all routes on that controller (only one in this case).

import { Request, Response, Middleware, IMiddleware } from "@xernois/easy-backend";

@Middleware({ singleton: false })
export default class LoggerMiddleware implements IMiddleware {

        execute(req: Request, res: Response) { 
                console.log(req.method, req.url, req.headers.host, req.headers['user-agent'])
        }
}

Middleware implements the IMiddleware interface and the execute method, which is basically a handler. In this case, the middleware just logs each request method, url, host and user-agent.

📂 Structure

There are no specific rules for file structure, although I would probably advise users to use the example structure.

│   index.ts
│
└───src
    ├───controllers
    │       mainController.ts
    │
    ├───middlewares
    │       loggerMiddleware.ts
    │
    ├───resolvers
    │       UserResolver.ts
    │
    └───services
            dataService.ts
            mainService.ts
            secondService.ts

But at this point it's really a matter of preference and also the size of the project.

🏁 Getting started

🚧 Comming soon