Simple CRUD example with NodeJS, Sequelize, Swagger and MySQL
- NodeJS Express v4.16.4
- Sequelize v4.38.0
- Swagger UI v3.20.1
- MySQL
The objective of this guide is to make a NodeJS Express web API connecting with a MySQL database by using the Sequelize ORM (Object-relational mapping). The Swagger UI will be used to test the API.
-
Run the script located at "/docs/crud.sql" to create the database on MySQL Workbench or on another program of your preference.
-
Install the node modules running the comands below at the root folder:
npm install
- Run the API:
npm run dev
- Acess the URL:
http://localhost:3000
The structure of the project is this:
The "server.js" file creates a MySQL pool to allow multiple connections:
The "/config/config.json" contains database connections for different environments. They are used by the "/models/index.js" file during the Sequelize initialization:
The "/models" folder contains the Sequelize table models. For example: the "profiles" model.
The "users" model makes reference to the "profiles" model:
The "/plugins/transaction.js" file is responsible for making the transaction's commit and rollback:
The "/controllers/users.js" has the GET/POST/PUT/DELETE methods: