Alfie Kemp

Alfie Kemp

1656128181

Building REST API using Node.js, Express.js, Sequelize.js & PostgreSQL

How to Create a REST API using Node.js, Express.js, Sequelize.js & PostgreSQL

In this tutorial, we will show how to create a little complex table association or relationship with CRUD (Create, Read, Update, Delete) operations. A comprehensive step by step tutorial on building REST API using Node.js, Express.js, Sequelize.js, and PostgreSQL. 

The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js
  2. PostgreSQL Server
  3. Express.js
  4. Sequelize.js
  5. Terminal or Command Line
  6. Text Editor or IDE

We assume that you have installed the PostgreSQL server in your machine or can use your own remote server (we are using PostgreSQL 9.5.13). Also, you have installed Node.js on your machine and can run `node`, `npm`, or `yarn` command in your terminal or command line. Next, check their version by type these commands in your terminal or command line.

node -v
v8.11.1
npm -v
6.1.0
yarn -v
1.7.0

1: Create Express.js Project and Install Required Modules

Open your terminal or node command line the go to your projects folder. First, install express-generator using this command.

sudo npm install express-generator -g

Next, create an Express.js app using this command.

express node-sequelize --view=ejs

This will create Express.js project with the EJS view instead of the Jade view template because using '--view=ejs' parameter. Next, go to the newly created project folder then install node modules.

cd node-sequelize && npm install

You should see the folder structure like this.

Node.js, Express.js, Sequelize.js and PostgreSQL RESTful API - Project Structure

There's no view yet using the latest Express generator. We don't need it because we will create a RESTful API.

2: Add and Configure Sequelize.js Module and Dependencies

Before installing the modules for this project, first, install Sequelize-CLI by type this command.

sudo npm install -g sequelize-cli

To install the Sequelize.js module, type this command.

npm install --save sequelize

Then install the module for PostgreSQL.

npm install --save pg pg-hstore

Next, create a new file at the root of the project folder that initializes the Sequelize configuration.

touch .sequelizerc

Open and edit that file then add these lines of codes.

const path = require('path');

module.exports = {
  "config": path.resolve('./config', 'config.json'),
  "models-path": path.resolve('./models'),
  "seeders-path": path.resolve('./seeders'),
  "migrations-path": path.resolve('./migrations')
};

That files will tell Sequelize initialization to generate config, models, seeders, and migrations files to specific directories.  Next, type this command to initialize the Sequelize.

sequelize init

That command will create `config/config.json`, `models/index.js`, `migrations`, and `seeders` directories and files. Next, open and edit `config/config.json` then make it like this.

{
  "development": {
    "username": "codequs",
    "password": "codequs12",
    "database": "node_sequelize",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "root",
    "password": "codequs12",
    "database": "node_sequelize",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "username": "root",
    "password": "codequs12",
    "database": "node_sequelize",
    "host": "127.0.0.1",
    "dialect": "postgres"
  }
}

We use the same configuration for all the environment because we are using the same machine, server, and database for this tutorial.

Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.

psql postgres --u postgres

Next, type this command for creating a new user with a password then give access for creating the database.

postgres-# CREATE ROLE djamware WITH LOGIN PASSWORD 'codequs12';
postgres-# ALTER ROLE codequs CREATEDB;

Quit `psql` then log in again using the new user that previously created.

postgres-# \q
psql postgres -U codequs

Enter the password, then you will enter this `psql` console.

psql (9.5.13)
Type "help" for help.

postgres=>

Type this command to creating a new database.

postgres=> CREATE DATABASE node_sequelize;

Then give that new user privileges to the new database then quit the `psql`.

postgres=> GRANT ALL PRIVILEGES ON DATABASE node_sequelize TO codequs;
postgres=> \q

3: Create or Generate Sequelize Models and Migrations

We will use Sequelize-CLI to generate a new Sequelize model. Type this command to create a model for `Classroom`, `Student`, `Lecturer`, `Course`, and `StudentCourse`.

sequelize model:create --name Classroom --attributes class_name:string
sequelize model:create --name Student --attributes classroom_id:integer,student_name:string
sequelize model:create --name Lecturer --attributes lecturer_name:string
sequelize model:create --name Course --attributes lecturer_id:integer,course_name:string
sequelize model:create --name StudentCourse --attributes student_id:integer,course_id:integer

That command creates a model file to the model's folder and a migration file to folder migrations. Next, modify `models/classroom.js` then add association with `Student` model inside `associate` function.

  class Classroom extends Model {
    static associate(models) {
      Classroom.hasMany(models.Student, {
        foreignKey: 'classroom_id',
        as: 'students',
      });
    }
  };

Next, modify `models/student.js` then add association with `Classroom` and `Coursemodel` models inside `associate` function.

  class Student extends Model {
    static associate(models) {
      Student.belongsTo(models.Classroom, {
        foreignKey: 'classroom_id',
        as: 'classroom'
      });
      Student.belongsToMany(models.Course, {
        through: 'StudentCourse',
        as: 'courses',
        foreignKey: 'student_id'
      });
    }
  };

Next, modify `models/lecturer.js` then add the association with the `Course` model inside the `associate` function.

  class Lecturer extends Model {
    static associate(models) {
      Lecturer.hasOne(models.Course, {
        foreignKey: 'lecturer_id',
        as: 'course',
      });
    }
  };

Next, modify `models/course.js` then add association with `Student` and `Lecturer` models inside `associate` function.

  class Course extends Model {
    static associate(models) {
      Course.belongsToMany(models.Student, {
        through: 'StudentCourse',
        as: 'students',
        foreignKey: 'course_id'
      });
      Course.belongsTo(models.Lecturer, {
        foreignKey: 'lecturer_id',
        as: 'lecturer'
      });
    }
  };

Finally, for migrations, there's nothing to change, and they all ready to generate the table to the PostgreSQL Database. Type this command to generate the table to the database using Sequelize.

sequelize db:migrate


4: Create Express Controller and Router for Classroom Model

To create the controller, first, create a folder for controllers and a new Javascript file by type these commands.

mkdir controllers
touch controllers/classroom.js

Open and edit `controllers/classroom.js` then add these lines of codes.

const Classroom = require('../models').Classroom;
const Student = require('../models').Student;

module.exports = {
  list(req, res) {
    return Classroom
      .findAll({
        include: [{
          model: Student,
          as: 'students'
        }],
        order: [
          ['createdAt', 'DESC'],
          [{ model: Student, as: 'students' }, 'createdAt', 'DESC'],
        ],
      })
      .then((classrooms) => res.status(200).send(classrooms))
      .catch((error) => { res.status(400).send(error); });
  },

  getById(req, res) {
    return Classroom
      .findByPk(req.params.id, {
        include: [{
          model: Student,
          as: 'students'
        }],
      })
      .then((classroom) => {
        if (!classroom) {
          return res.status(404).send({
            message: 'Classroom Not Found',
          });
        }
        return res.status(200).send(classroom);
      })
      .catch((error) => {
        console.log(error);
        res.status(400).send(error);
      });
  },

  add(req, res) {
    return Classroom
      .create({
        class_name: req.body.class_name,
      })
      .then((classroom) => res.status(201).send(classroom))
      .catch((error) => res.status(400).send(error));
  },

  update(req, res) {
    return Classroom
      .findByPk(req.params.id, {
        include: [{
          model: Student,
          as: 'students'
        }],
      })
      .then(classroom => {
        if (!classroom) {
          return res.status(404).send({
            message: 'Classroom Not Found',
          });
        }
        return classroom
          .update({
            class_name: req.body.class_name || classroom.class_name,
          })
          .then(() => res.status(200).send(classroom))
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },

  delete(req, res) {
    return Classroom
      .findByPk(req.params.id)
      .then(classroom => {
        if (!classroom) {
          return res.status(400).send({
            message: 'Classroom Not Found',
          });
        }
        return classroom
          .destroy()
          .then(() => res.status(204).send())
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },
};

In that controller, we have all CRUD (Create, Read, Update, and Delete) functions. To make this controller available via the controller's folder, add these files for declaring this controller file and other controllers files.

touch controllers/index.js

Open and edit that file then add these lines of Javascript codes.

const classroom = require('./classroom');

module.exports = {
  classroom,
};

For the router, we will use the existing router that generated by Express Generator. Open and edit `routes/index.js` then declare the Classroom controller after other variables.

const classroomController = require('../controllers').classroom;

Add these routes after the existing route for the Classroom controller.

router.get('/api/classroom', classroomController.list);
router.get('/api/classroom/:id', classroomController.getById);
router.post('/api/classroom', classroomController.add);
router.put('/api/classroom/:id', classroomController.update);
router.delete('/api/classroom/:id', classroomController.delete);

5: Create Express Controller and Router for Student Model

Type this command to create a controller and router file for a Student model.

touch controllers/student.js

Open and edit `controllers/student.js` then add these lines of codes that contain full CRUD function for the Student model.

const Student = require('../models').Student;
const Classroom = require('../models').Classroom;
const Course = require('../models').Course;

module.exports = {
  list(req, res) {
    return Student
      .findAll({
        include: [{
          model: Classroom,
          as: 'classroom'
        },{
          model: Course,
          as: 'courses'
        }],
        order: [
          ['createdAt', 'DESC'],
          [{ model: Course, as: 'courses' }, 'createdAt', 'DESC'],
        ],
      })
      .then((students) => res.status(200).send(students))
      .catch((error) => { res.status(400).send(error); });
  },

  getById(req, res) {
    return Student
      .findByPk(req.params.id, {
        include: [{
          model: Classroom,
          as: 'classroom'
        },{
          model: Course,
          as: 'courses'
        }],
      })
      .then((student) => {
        if (!student) {
          return res.status(404).send({
            message: 'Student Not Found',
          });
        }
        return res.status(200).send(student);
      })
      .catch((error) => res.status(400).send(error));
  },

  add(req, res) {
    return Student
      .create({
        classroom_id: req.body.classroom_id,
        student_name: req.body.student_name,
      })
      .then((student) => res.status(201).send(student))
      .catch((error) => res.status(400).send(error));
  },

  update(req, res) {
    return Student
      .findByPk(req.params.id, {
        include: [{
          model: Classroom,
          as: 'classroom'
        },{
          model: Course,
          as: 'courses'
        }],
      })
      .then(student => {
        if (!student) {
          return res.status(404).send({
            message: 'Student Not Found',
          });
        }
        return student
          .update({
            student_name: req.body.student_name || student.student_name,
          })
          .then(() => res.status(200).send(student))
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },

  delete(req, res) {
    return Student
      .findByPk(req.params.id)
      .then(student => {
        if (!student) {
          return res.status(400).send({
            message: 'Student Not Found',
          });
        }
        return student
          .destroy()
          .then(() => res.status(204).send())
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },
};

Next, open and edit `controllers/index.js` then register the Student controller in that file.

const classroom = require('./classroom');
const student = require('./student');

module.exports = {
  classroom,
  student,
};

Next, open and edit `routes/index.js` then add a required variable for the student controller.

const studentController = require('../controllers').student;

Add the routes for all CRUD functions of the student controller.

router.get('/api/student', studentController.list);
router.get('/api/student/:id', studentController.getById);
router.post('/api/student', studentController.add);
router.put('/api/student/:id', studentController.update);
router.delete('/api/student/:id', studentController.delete);

6: Create Express Controller and Router for Lecturer Model

Type this command to create a controller and router file for the Lecturer model.

touch controllers/lecturer.js

Open and edit `controllers/lecturer.js` then add these lines of codes that contain full CRUD function for the Lecturer model.

const Lecturer = require('../models').Lecturer;
const Course = require('../models').Course;

module.exports = {
  list(req, res) {
    return Lecturer
      .findAll({
        include: [{
          model: Course,
          as: 'course'
        }],
        order: [
          ['createdAt', 'DESC'],
          [{ model: Course, as: 'course' }, 'createdAt', 'DESC'],
        ],
      })
      .then((lecturers) => res.status(200).send(lecturers))
      .catch((error) => { res.status(400).send(error); });
  },

  getById(req, res) {
    return Lecturer
      .findByPk(req.params.id, {
        include: [{
          model: Course,
          as: 'course'
        }],
      })
      .then((lecturer) => {
        if (!lecturer) {
          return res.status(404).send({
            message: 'Lecturer Not Found',
          });
        }
        return res.status(200).send(lecturer);
      })
      .catch((error) => res.status(400).send(error));
  },

  add(req, res) {
    return Lecturer
      .create({
        lecturer_name: req.body.lecturer_name,
      })
      .then((lecturer) => res.status(201).send(lecturer))
      .catch((error) => res.status(400).send(error));
  },

  update(req, res) {
    return Lecturer
      .findByPk(req.params.id, {
        include: [{
          model: Course,
          as: 'course'
        }],
      })
      .then(lecturer => {
        if (!lecturer) {
          return res.status(404).send({
            message: 'Lecturer Not Found',
          });
        }
        return lecturer
          .update({
            lecturer_name: req.body.lecturer_name || classroom.lecturer_name,
          })
          .then(() => res.status(200).send(lecturer))
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },

  delete(req, res) {
    return Lecturer
      .findByPk(req.params.id)
      .then(lecturer => {
        if (!lecturer) {
          return res.status(400).send({
            message: 'Lecturer Not Found',
          });
        }
        return lecturer
          .destroy()
          .then(() => res.status(204).send())
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },
};

Next, open and edit `controllers/index.js` then register the Lecturer controller in that file.

const classroom = require('./classroom');
const student = require('./student');
const lecturer = require('./lecturer');

module.exports = {
  classroom,
  student,
  lecturer,
};

Next, open and edit `routes/index.js` then add a required variable for the lecturer controller.

const lecturerController = require('../controllers').lecturer;

Add the routes for all CRUD functions of the lecturer controller.

router.get('/api/lecturer', lecturerController.list);
router.get('/api/lecturer/:id', lecturerController.getById);
router.post('/api/lecturer', lecturerController.add);
router.put('/api/lecturer/:id', lecturerController.update);
router.delete('/api/lecturer/:id', lecturerController.delete);

7: Create Express Controller and Router for Course Model

Type this command to create a controller and router file for the Course model.

touch controllers/course.js

Open and edit `controllers/course.js` then add these lines of codes that contain full CRUD function for the Course model.

const Course = require('../models').Course;
const Student = require('../models').Student;
const Lecturer = require('../models').Lecturer;

module.exports = {
  list(req, res) {
    return Course
      .findAll({
        include: [{
          model: Student,
          as: 'students'
        },{
          model: Lecturer,
          as: 'lecturer'
        }],
        order: [
          ['createdAt', 'DESC'],
          [{ model: Student, as: 'students' }, 'createdAt', 'DESC'],
        ],
      })
      .then((courses) => res.status(200).send(courses))
      .catch((error) => { res.status(400).send(error); });
  },

  getById(req, res) {
    return Course
      .findByPk(req.params.id, {
        include: [{
          model: Course,
          as: 'course'
        }],
      })
      .then((course) => {
        if (!course) {
          return res.status(404).send({
            message: 'Course Not Found',
          });
        }
        return res.status(200).send(course);
      })
      .catch((error) => res.status(400).send(error));
  },

  add(req, res) {
    return Course
      .create({
        course_name: req.body.course_name,
      })
      .then((course) => res.status(201).send(course))
      .catch((error) => res.status(400).send(error));
  },

  update(req, res) {
    return Course
      .findByPk(req.params.id, {
        include: [{
          model: Course,
          as: 'course'
        }],
      })
      .then(course => {
        if (!course) {
          return res.status(404).send({
            message: 'Course Not Found',
          });
        }
        return course
          .update({
            course_name: req.body.course_name || classroom.course_name,
          })
          .then(() => res.status(200).send(course))
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },

  delete(req, res) {
    return Course
      .findByPk(req.params.id)
      .then(course => {
        if (!course) {
          return res.status(400).send({
            message: 'Course Not Found',
          });
        }
        return course
          .destroy()
          .then(() => res.status(204).send())
          .catch((error) => res.status(400).send(error));
      })
      .catch((error) => res.status(400).send(error));
  },
};

Next, open and edit `controllers/index.js` then register the Course controller in that file.

const classroom = require('./classroom');
const student = require('./student');
const lecturer = require('./lecturer');
const course = require('./course');

module.exports = {
  classroom,
  student,
  lecturer,
  course,
};

Next, open and edit `routes/index.js` then add a required variable for the course controller.

const courseController = require('../controllers').course;

Add the routes for all CRUD functions of the course controller.

router.get('/api/course', courseController.list);
router.get('/api/course/:id', courseController.getById);
router.post('/api/course', courseController.add);
router.put('/api/course/:id', courseController.update);
router.delete('/api/course/:id', courseController.delete);

8: Advance Express Route and Function for Association

Now, we have to make the association more useful. To make a Classroom include the students, add this function to `controllers/classroom.js`.

  addWithStudents(req, res) {
    return Classroom
      .create({
        class_name: req.body.class_name,
        students: req.body.students,
      }, {
      	include: [{
          model: Student,
          as: 'students'
        }]
      })
      .then((classroom) => res.status(201).send(classroom))
      .catch((error) => res.status(400).send(error));
  },

Next, add this new function to the route file `routes/index.js`.

router.post('/api/classroom/add_with_students', classroomController.addWithStudents);

To add a lecturer include a course, add this function to `controllers/lecturer.js`.

  addWithCourse(req, res) {
    return Lecturer
      .create({
        lecturer_name: req.body.lecturer_name,
        course: req.body.course
      }, {
        include: [{
          model: Course,
          as: 'course'
        }]
      })
      .then((lecturer) => res.status(201).send(lecturer))
      .catch((error) => res.status(400).send(error));
  },

Next, add this new function to the route file `routes/index.js`.

router.post('/api/lecturer/add_with_course', lecturerController.addWithCourse);

To add a course for a student, add this function to `controllers/student.js`.

  addCourse(req, res) {
    return Student
      .findByPk(req.body.student_id, {
        include: [{
          model: Classroom,
          as: 'classroom'
        },{
          model: Course,
          as: 'courses'
        }],
      })
      .then((student) => {
        if (!student) {
          return res.status(404).send({
            message: 'Student Not Found',
          });
        }
        Course.findByPk(req.body.course_id).then((course) => {
          if (!course) {
            return res.status(404).send({
              message: 'Course Not Found',
            });
          }
          student.addCourse(course);
          return res.status(200).send(student);
        })
      })
      .catch((error) => res.status(400).send(error));
  },

Next, add this new function to the route file `routes/index.js`.

router.post('/api/student/add_course', studentController.addCourse);

That's a few of the Association features that might be useful for your project. We will add another useful function to this article later.

9: Run and Test The Node, Express, Sequelize, and PostgreSQL REST API

Type this command to run the application.

nodemon

Open the new terminal tab or command line tab then type this command for save or persist classroom data include with students.

curl -i -X POST -H "Content-Type: application/json" -d '{ "class_name":"Class A","students": [{ "student_name":"Mya Lynch" },{ "student_name":"Joseph Norton" },{ "student_name":"Dedric Reinger" }] }' localhost:3000/api/classroom/add_with_students

To see data persist to PostgreSQL table, open a new terminal tab then run `psql`.

psql postgres -U codequs

Connect to the database then running the queries.

postgres=> \c node_sequelize
node_sequelize=> SELECT * FROM public."Classrooms";

 id | class_name |         createdAt          |         updatedAt
----+------------+----------------------------+----------------------------
  2 | Class A    | 2021-07-24 09:18:30.062+07 | 2021-07-24 09:18:30.062+07
(1 row)

node_sequelize=> SELECT * FROM public."Students" WHERE classroom_id=2;

id | classroom_id | student_name |         createdAt          |         updatedAt
----+--------------+--------------+----------------------------+----------------------------
 1 |            2 | Mya Lynch     | 2021-07-24 09:18:30.125+07 | 2021-07-24 09:18:30.125+07
 2 |            2 | Joseph Norton | 2021-07-24 09:18:30.125+07 | 2021-07-24 09:18:30.125+07
 3 |            2 | Dedric Reinger| 2021-07-24 09:18:30.125+07 | 2021-07-24 09:18:30.125+07
(3 rows)

Using `curl` you just get a classroom then the students will be included with the response.

curl -i -H "Accept: application/json" localhost:3000/api/classroom/2

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 512
ETag: W/"200-9RPafOJtDdkqqMBVkSNCFoQ3p9s"
Date: Tue, 24 Jul 2021 03:18:45 GMT
Connection: keep-alive

{"id":2,"class_name":"Class A","createdAt":"2021-07-24T02:18:30.062Z","updatedAt":"2021-07-24T02:18:30.062Z","students":[{"id":1,"classroom_id":2,"student_name":"Mya Lynch","createdAt":"2021-07-24T02:18:30.125Z","updatedAt":"2021-07-24T02:18:30.125Z"},{"id":2,"classroom_id":2,"student_name":"Joseph Norton","createdAt":"2018-07-24T02:18:30.125Z","updatedAt":"2021-07-24T02:18:30.125Z"},{"id":3,"classroom_id":2,"student_name":"Norton Reinger","createdAt":"2021-07-24T02:18:30.125Z","updatedAt":"2021-07-24T02:18:30.125Z"}]}

Run this `curl` for save or persist Lecturer, Course, and Student/Course data.

curl -i -X POST -H "Content-Type: application/json" -d '{ "lecturer_name":"Imani Gorczany","course": { "course_name":"English Grammar" }}' localhost:3000/api/lecturer/add_with_course
curl -i -X POST -H "Content-Type: application/json" -d '{ "student_id":1,"course_id": 1}' localhost:3000/api/student/add_course

Now, you can see the data exists using `psql` query for each table.

👉  Build a Rest Api with NodeJS, Express and PostgreSQL With Video Tutorial

In this video we build a rest api with NodeJS (JavaScript) and PostreSQL.

In this video we tackle 
* routing concepts
* the express framework
* how to use Postman to test your routes
* how to create a database in the psql shell
* performing SQL queries
* callback functions

#nodejs #postgresql #javascript 

What is GEEK

Buddha Community

Building REST API using Node.js, Express.js, Sequelize.js & PostgreSQL
Charity  Ferry

Charity Ferry

1620812402

Node.js Postgresql tutorial: Build a simple REST API with Express

Prerequisites

  1. You have Node.js (preferably Node 14.x) installed and running on your machine (or Node.js running with a docker container).
  2. You are aware of how Node.js generally works and also have a bit of Express Js experience.
  3. Having some knowledge of Git and GitHub will be really useful.
  4. For the database we will use a free database on [ElephantSQL], so please register and set up a free PostgreSQL database there. Of course, you should know how a relational database works.
  5. You are able to code using an IDE. I will be using VS Code as an editor but you are free to use any code editor of your choice for this Node.js PostgreSQL tutorial.

#postgresql #express js #rest api #node.js #postgresql tutorial

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Enoch Barcenas

Enoch Barcenas

1594026159

Building REST API using Node, Express, Sequelize and PostgreSQL

Step by step tutorial on building REST API using Node.js, Express.js, Sequelize.js and PostgreSQL.

A comprehensive step by step tutorial on building RESTful API using Node.js, Express.js, Sequelize.js, and PostgreSQL. In this tutorial, we will show how to create a little complex table association or relationship with CRUD (Create, Read, Update, Delete) operations. So, the association or relationship will be like this diagram.

This tutorial divided into several steps:

Step #1: Create Express.js Project and Install Required Modules
Step #2: Add and Configure Sequelize.js Module and Dependencies
Step #3: Create or Generate Sequelize Models and Migrations
Step #4: Create Express Controller and Router for Classroom Model
Step #5: Create Express Controller and Router for Student Model
Step #6: Create Express Controller and Router for Lecturer Model
Step #7: Create Express Controller and Router for Course Model
Step #8: Advance Express Route and Function for Association
Step #9: Run and Test The Node, Express, Sequelize, and PostgreSQL REST API

Full article here:
https://www.djamware.com/post/5b56a6cc80aca707dd4f65a9/nodejs-expressjs-sequelizejs-and-postgresql-restful-api

Source code:
https://github.com/didinj/node-express-postgresql-sequelize.git

#api #node #express #postgresql #sequelize

Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

Kieran  Stroman

Kieran Stroman

1591359240

[Hindi] Express.js Tutorial: Build RESTful APIs with Node and Express - Part 1

Express.js Tutorial: Building RESTful APIs with Node Express. nodejs tutorial with api building with get and post methods.

#express #apis #node #restful apis #express.js