Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Code Express with ORM and MySQL/MariaDB

NotificationsYou must be signed in to change notification settings

impactbyte-learn/code-restapi-orm-sqldatabase

Repository files navigation

Greenkeeper badge

Code example to build a REST API with ORM and SQL Database.

Technologies:

Table of Contents


Preparation

Database Installation

We recommend usingmariadb instead ofmysql.Although thenode adapter can be usingmysql2 adapter.

macOS:

brew install mariadbbrew services start mariadb

Ubuntu:

Setup database for all environments

In local.

# for developmentCREATEDATABASEyourdatabasename

In remote server.

# for testCREATEDATABASEyourdatabasename_test# for productionCREATEDATABASEyourdatabasename

Installation and Configuration

Install dependencies.

yarn

This will also run thesetup script automatically.

yarn setup# this will copy .env.schema to .env if not exist yet

Then edit.env contents in your editor. Refer to.env.defaults for the default values.

DEVELOPMENT_DB_USERNAME=yourusernameDEVELOPMENT_DB_PASSWORD=yourpasswordDEVELOPMENT_DB_NAME=yourdatabasenameDEVELOPMENT_DB_HOST=localhostDEVELOPMENT_DB_PORT=3306DEVELOPMENT_DB_DIALECT=mysqlTEST_DB_USERNAME=yourusernameTEST_DB_PASSWORD=yourpasswordTEST_DB_NAME=yourdatabasename-testTEST_DB_HOST=localhostTEST_DB_PORT=3306TEST_DB_DIALECT=mysqlPRODUCTION_DB_USERNAME=yourusernamePRODUCTION_DB_PASSWORD=yourpasswordPRODUCTION_DB_NAME=yourdatabasenamePRODUCTION_DB_HOST=0.0.0.0PRODUCTION_DB_PORT=3306PRODUCTION_DB_DIALECT=mysql

Create thatyourdatabase (change this) database to your own database server.You can use CLI or GUI application.

Runmigrate scriptonly once to run the migration files, create the tables into the database.

yarn migrate# this will run all migrations/*.js

You can runseed scriptonly once also to run the seeder files, insert demo data into the database.

yarn seed# this will run all seeders/*.js

Running

Only run after the preparation, installation, and configuration are finished.

Development

yarn dev

Production

yarn start

Extra Information

REST API Endpoints

EndpointHTTPDescription
/GETGet root API
/usersGETGet all users
/users/:idGETGet one user by id
/usersPOSTCreate new user
/users/:idPUTUpdate one user by id
/users/:idDELETEDelete one user by id
/usersDELETEDelete all users

Request body example

{"email":"yourname@yourdomain.com","password":"yourpassword","username":"yourusername","name":"Your Full Name"}

Data Schema

Data Schema

Users

{"id":0,"email":"","password":"","salt":"","username":"","name":""}

Tasks

{"id":0,"user_id":0,"text":""}

How to Setup Sequelize

Follow this official guide:http://docs.sequelizejs.com/manual/tutorial/migrations.html

Installsequelize dependencies in your project.

yarn add sequelize mysql2

Usesequelize-cli to initialize and configure the project.

# install sequelize-cli globallyyarn global add sequelize-cli sequelize mysql2# so you can use it anywheresequelize init# change config.json to config.js# change '/../config/config.js' in models/index.js# configure config.js based on your database settings# change database name, username, password, host, port, dialect# generate model via clisequelize model:generate --name User --attributes username:string,email:string# edit migrations file# migrations/20180000000000-create-user.js# edit models file# models/user.js# do the migration from the configuration to the actual databasesequelize db:migrate# generate seeder via clisequelize seed:generate --name demo-users# edit seeders file# seeders/20180000000000-demo-users.js# do the seeding from the configuration to the actual databasesequelize db:seed:all

How to Integrate with Express

Change theserver.listen code block.

server.listen(port,function(){console.log('Express server listening on port '+server.address().port)})server.on('error',onError)server.on('listening',onListening)

Into this, to be wrapped withmodels.sequelize.

constmodels=require('./models')// ...models.sequelize.sync().then(function(){server.listen(port,function(){console.log('Express server listening on port '+server.address().port)debug('Express server listening on port '+server.address().port)})server.on('error',onError)server.on('listening',onListening)})

Use the model from anywhere. For instance, in your controller functions.

constmodels=require('../../models')// ...models.User.findAll().then(users=>{res.send({      users})}).catch(error=>{res.status(400).send({      error})})

Runexpress server as usual.

Database Dump

How to backup/export & restore/import database from/to a file.

Export:

mysqldump yourdatabase --single-transaction --user=yourusername -p> yourfile.sql

Import:

mysql yourdatabase --user=yourusername -p< yourfile.sql

How to Deploy with Heroku

You can also follow the official guides or community articles:

Create and login to your account on Heroku.

On Heroku Dashboard

Create the app on Heroku.

Setup your "Config Vars":https://dashboard.heroku.com/apps/yourappname/settings, then "Reveal Config Vars".

Put yourKEY andVALUE respectively.

PRODUCTION_DB_USERNAME = yourusernamePRODUCTION_DB_PASSWORD = yourpasswordPRODUCTION_DB_NAME = yourdatabasenamePRODUCTION_DB_HOST = 0.0.0.0PRODUCTION_DB_PORT = 3306PRODUCTION_DB_DIALECT = mysql

Make sure it's set correctly.

You can also make it auto deploy in "Deployment Method" by connecting with GitHub:https://dashboard.heroku.com/apps/yourappname/deploy/github, then "Enable Automatic deploys".

On Your Local Computer

Install Heroku toolbelt CLI.

# on linuxsudo apt install heroku# on macbrew install heroku

Login in CLI.

heroku login

CreateProcfile and add this line.It will be used for Heroku on how to start the app.Procfile itself is defined by [node-foreman](https://github.com/strongloop/node-foreman.

web: yarn start

Createapp.json and add these lines.It will be used for Heroku to identify the app.

{"name":"yourappname","description":"Your App Description","repository":"https://github.com/yourusername/yourappname","keywords": ["your","key","words"],"image":"heroku/nodejs"}

You can also install Heroku in your development dependencies.Please note thatdevDependencies will not be installed on production.

yarn add --dev heroku

Test your local app as if run using Heroku.

herokulocal web

Test your local app as if run using Heroku onPRODUCTION mode/environment.

yarn start:production# this will run# NODE_ENV=production heroku local web

Go to your repo, then add heroku remote.

heroku git:remote -a yourappname# set git remote heroku to https://git.heroku.com/yourappname.git

Push to Heroku through Git.

git push heroku master

On Heroku server, the Heroku platform will in order:

  • Be cloned fresh either from push or GitHub new commit trigger.
  • Detect the repo if it's a Node.js app.
  • Create runtime environment, especially setNODE_ENV=production.
  • Install Node.js, npm, and yarn binaries.
  • Restore cache.
  • Build dependencies.
    • Install node modules.
    • Runinstall script. In this case, runnpm run setup andnpm run migrate scripts.
  • Run the dependency installation based onpackage.json'sdependencies.
  • RunProcfile'sweb script. In this case, runyarn start.

You can see those in details in "Activity" panel:https://dashboard.heroku.com/apps/yourappname/activity.

If there's something wrong with your database, connect to its server and resolve the issue.

About

Code Express with ORM and MySQL/MariaDB

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp