This is a HYF Project boilerplate for building a REST API. Let's refresh our minds on this. READ THIS SO POST
Before getting started with this repo, read and repeat the "Getting started" part of the Angular WebApp Repo, and get ready to collaborate in your team
Make sure you have these 4 installed
- Node.js version 7.3.0 or higher (easily manage Node version with NVM)
- Docker
- (Windows users only) Bash
Clone your copy of this repo as explained Angular WebApp Repo. Then:
// find where you cloned the repo
cd project-api/
npm install // Install NPM dependencies
sh database/create_database.sh // Install database
npm start
- node-db-migrate for managing the database structure using migrations
- expressjs for routing
- mysql2 for talking to MySQL with promise support
- dotenv for saving passwords etc safely.
Nice to read but not required to work:
Try to make a new entity (e.g. "products") and its MySQL table
- Go to
package.json
and checkout thescripts
section. It contains a couple of commands that can executenode-db-migrate
commands. The most essential ones are:node run migrate-up
node run migrate-down
node run create-migration {{migration-name}}
- Check if the database is running. Try to connect to the database by running
sh database/connect_database.sh
If it doesn't work, rerun thesh database/create_database.sh
script to start the db. To see if the mysql docker container is running you can typedocker ps
- To create a new table we run
npm run create-migration products
- Go to
./database/migrations/sqls/#####-products-up.sql
- Write
CREATE TABLE products
command with some fields - DO NOT FORGET EVER, write the DOWN command by opening the
./database/migrations/sqls/#####-products-down.sql
and writingDROP TABLE products
. The down migration is always the command that undos the up command` - Save both migrations
- Run
npm run migrate-up
- Unless you get errors, your table should be created!
Try to make a new entity (e.g. "products") and its corresponding route
- Create a file under
./lib/routers
and call itproducts.js
- Take a look at
students.js
orteachers.js
. What the file does is: start a newexpress.Router()
object, add some routes to it (e.g.router.get
orrouter.post
and then export that router). Do the same forproducts.js
. - Add the file to the main express application in
./lib/app.js
by requiring it and giving it a path. Under routers, we define the base path to which our products router will be added. Express will "merge" paths from the main router with the childproducts
router. - Try it out! go to your new path in your browser or using
curl -XGET 'localhost:3000/api/v1/products'
// Shell:
sh database/connect_database.sh
// Once connected
USE hyf_db;