DEV Community

Chukwuemeka Igbokwe
Chukwuemeka Igbokwe

Posted on

Developing REST APIs with ExpressWebJs v2(A Nodejs Framework) part 1.

Alt Text

ExpressWebJs is a Node FrameWork with expressive and organised syntax that runs on all major operating systems. It provides the starting point for creating your node project, allowing you to focus more on developing your amazing solution.

ExpressWebJs focuses on providing developer experience and powerful features such as dependency injection,database abstraction layer for both SQL and NOSQL, robust routing, code structure, application configuration, testing and more.

There are some built in features of ExpressWebJs

. Robust routing
. Focus on high performance
. Super-high test coverage
. HTTP helpers (redirection, caching, etc)
. Support for both SQL and NOSQL database
. Well organised and structured.
. Supports Use Of Dependency Injection
. Supports websocket
. Highly scalable
. Events and Listeners
. Queues
. Task Scheduling

Building an employee record API with ExpressWebJs

At company X, we have many employees. We are asked to build an app to manage our employee record. The front end app will be built with Vuejs or ReactJs. However, it needs to pull data from a source and also push to it. We need an API which we are going to develop with ExpressWebJs.

This is what we need our API to do:
. Get all employees
. Get an employee
. Add new employee
. Edit employee record
. Delete an employee

For the endpoints, we will be looking at:
. GET /api/employees
. GET /api/employees/6
. POST /api/employees
. PATCH /api/employees/6
. DELETE /api/employees/6

Next we will look at employees attribute:
. name
. email
. phone
. location
. country
. state

Install ExpressWebJs

Run the following command in your terminal to create a new project with ExpressWebJs:

  npx expresswebcli new employeesApp
Enter fullscreen mode Exit fullscreen mode

cd into your newly created project.

  cd employeesApp
Enter fullscreen mode Exit fullscreen mode

Now run npm install to install all dependencies.

Copy example.env into .env file with the following command

 cp example.env .env
Enter fullscreen mode Exit fullscreen mode

Once that is done, you can now configure your database in the .env file.

Remember: ExpressWebJs supports Both SQL and NOSQL Database.

For this tutorial, we will be working with mysql db (sql database).

Now, run npm run dev to serve the project. Head over to your browser.

Migration:

ExpressWebJs comes with Maker command, which is the command line interface. Maker exists at the root of your application as the maker script and provides a number of helpful commands that can assist you while you build your application. To view a list of all available Maker commands, you may use the help command:

  node maker -h
Enter fullscreen mode Exit fullscreen mode

So for us to create our employees migration and model, we can do that like so:

  node maker make-sql-model employees -m
Enter fullscreen mode Exit fullscreen mode

-m tells Maker to also generate out migration while creating our model.

The new migration will be placed in Database/Migrations .
Each migration file name contains a timestamp, which allows ExpressWebJs to determine the order of the migrations. Next, we'll modify the recently created migration to include the attributes we need for the employees table.

Open up the migration file and modify it like so:

  /**
   * Migration layout file.
   * Assign your table name to the tableName variable.
   * Remember, it's always in plural
  */
  let tableName = "employees";
  exports.up = function (knex) {
  return knex.schema.createTable(tableName, (table) => {
    table.increments("id");
    table.string("name").notNullable();
    table.string("email").unique().notNullable();
    table.string("phone").notNullable();
    table.string("location").notNullable();
    table.string("country").notNullable();
    table.string("state").notNullable();
    table.timestamps(true, true);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable(tableName);
};
Enter fullscreen mode Exit fullscreen mode

Now, go ahead and run the migration like so:

   node maker run-sql-migration
Enter fullscreen mode Exit fullscreen mode

Check your database. You should now have the employees and migrations tables present.

model

when we ran the node maker make-sql-model employees
-m
ExpressWebjs generated our model in the App/Model directory.

App/Model/Employees_model.js

   "use strict";
   const Model = require("@elucidate/Model");
   class Employees extends Model {
      static get tableName() {
         return "employees";
      }
   }

   module.exports = Employees;
Enter fullscreen mode Exit fullscreen mode

Set up Employees Controller

To create a new controller called EmployeesController, use the maker command for controller:

  node maker make-controller EmployeesController -r
Enter fullscreen mode Exit fullscreen mode

where -r will tell Maker to generate our controller with resource methods.

Our Controller will be generated in App/Http/Controller directory

App/Http/Controller/EmployeesController:

  "use strict";

        class EmployeesController{
          /**
           * Display a listing of the resource.
           */
          index = async (req, res, next) =>{
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Show the form for creating a new resource.
           *
           * @return Response
           */
          create = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Store a newly created resource in storage.
           * @param  Request 
           * @return Response
           */
          store = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Display the specified resource.
           * @param  Request
           * @return Response
           */
          show = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Show the form for editing the specified resource.
           * @param  Request
           * @return Response
           */
          edit = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Update the specified resource in storage.
           * @param  Request
           * @return Response
           */
          update = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Remove the specified resource from storage.
           *
           * @param Request
           * @return Response
           */
          destroy = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }
        }

        module.exports = EmployeesController;

Enter fullscreen mode Exit fullscreen mode

We will fill up our EmployeesController in a bit.

Set up Routes

Routing is fairly straight-forward. Open up Routes/api.js and modify it like so:

   "use strict";
   const Route = require("@routerManager");
   /*
    |---------------------------------------------------------
    | Api route   
    |---------------------------------------------------------
    |
    | Here is where you can register your application routes. 
    | These
    | routes are loaded by the RouteProvider. Now create 
    | something great!
    |
  */

Route.get("/", (req, res) => {
  res.json({ Message: "Welcome To ExpressWebjs" });
});

Route.group("/employees", () => {
  Route.get("/","EmployeesController@index");

  Route.get("/:id", "EmployeesController@show");

  Route.post("/", "EmployeesController@store");

  Route.patch("/", "EmployeesController@update");

  Route.delete("/:id", "EmployeesController@destroy");
});

module.exports = Route.exec;
Enter fullscreen mode Exit fullscreen mode

We will start developing the business logic in part 2.

To read more about ExpressWebJs, visit the Documentation site at ExpressWebJs

You can follow me on twitter @EmekaIgbokwe
You can follow ExpressWebJs on twitter @expresswebjs
and don't forget to star on github ExpressWebJs

Please, let me know if you have any questions in the comment section. 😊

Top comments (0)