0.0.10 • Published 7 months ago

@xernois/easy-backend v0.0.10

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

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

0.0.3

10 months ago

0.0.10

7 months ago

0.0.9

7 months ago

0.0.8

8 months ago

0.0.5

8 months ago

0.0.4

10 months ago

0.0.7

8 months ago

0.0.6

8 months ago

0.0.2

1 year ago

0.0.1

1 year ago