32
loading...
This website collects cookies to deliver better user experience
Git is used for version control. It will provide us
with a convenient command line interface to save
different versions of our code and commit them to github
Github is a code hosting platform that hosts a Remote
Repository of our code. We can use Git to push our code
to Github and share it with the world.
Postgres is the database system we will be using for
this project. There are others like SQLite, MySQL,
Oracle, and more. But I know Postgres so that is what I
will be showing in this guide.
pgAdmin is technically not necessary for any part of
this process. I use it in my workflow because I like the
GUI it provides to manage the database and write SQL
queries.
Heroku CLI is the command line interface for Heroku.
This is going to allow us to push our git code to Heroku,
and there are other useful functions for dealing with
Heroku in there.
You can use your text editor of choice, mine is VSCode
This is javascript runtime to run javascript code
outside of the browser. This will also allow us to run
npm
commands to install dependencies into our project.
production-db-tutorial
. To do this I open a new terminal.cd ~/Desktop/side-projects
to change directories.mkdir production-db-tutorial
to create the new project directory.cd production-db-tutorial
to move to my newly created project folder and run code .
to open it in Visual Studio Code.code .
command opened a new VSCode window..env
and a file called index.js
to the root of the project. Then we can run npm init -y
to create a new package.json
file as well. This is where we will track the metadata of our application and can add npm
scripts to shorten our command line syntax later. package.json
so we will be able to run the application. My scripts object looks like this."scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
npm i -D nodemon
and this will install nodemon as a dev dependency. Finally run npm i cors dotenv express knex pg
to install cors, dotenv, express, knex, and pg as your normal dependencies. After that your package.json
should look a little like this. package.json
file. Also take note of the package-lock.json
and the node_modules folder. If you have followed up to this point you are currently on track to setting up a database!.env
file lets create some environment variables for the project (these will be explained when we implement them later)PORT=5000
NODE_ENV=development
index.js
file and create the server.require('dotenv').config()
const express = require('express')
const cors = require('cors')
const server = express()
const port = process.env.PORT || 8000
server.use(cors())
server.use(express.json())
server.get('/', (req, res) => {
res.send('<h1>This is a test application</h1>')
})
server.listen(port, () => {
console.log(`\n=== Server listening on port ${port} ===\n`)
})
require('dotenv').config()
.env
file.const express = require('express')
const cors = require('cors')
const server = express()
const port = process.env.PORT || 8000
process.env.PORT
first, so in this case it will access PORT=5000
from the .env
file we created earlier and use 5000 as the port. But if the server doesn't find a PORT in the .env
then it will default to use port 8000 as a backup by default.server.use(cors())
server.use(express.json())
server.get('/', (req, res) => {
res.send('<h1>This is a test application</h1>')
})
server.listen(port, () => {
console.log(`\n=== Server listening on port ${port} ===\n`)
})
npm run server
to start the server with nodemon. http://localhost:5000/
you should see this.npx gitignore node
. This will create a .gitignore
file that tells git what we don't want it to save in version control. This is very useful to store secrets like API keys. Then run git add .
to add all of our current files, and git commit -m 'first commit'
to commit our changes with a commit message. git branch -M main
changes our primary branch from master to main. Follow this by adding our remote repository locally. I did this by running git remote add origin https://github.com/tgrede/production-db-tutorial.git
. Once added you can push by running git push -u origin main
git add README.md
I used git add .
to add all the changed files..env
file to match the information from your database configuration that you just went through. DB_HOST
should be the host/address from when you created your server, in my case I used localhost as my host. DB_USER
by default should be postgres. postgres is a superuser that is created when you install postgres and so by default postgres is the owner of the postgres database server.DB_PASS
I blurred for obvious reasons but should be the password you set in pgAdmin4 when setting everything up.DB_NAME
is the name of the database you created, in my case it was tutorial-db
knex init
. This command uses the knex library we installed earlier to create a default knexfile.js
in the root of our project.knexfile.js
and replace the code with thisrequire('dotenv').config()
const pg = require('pg');
if (process.env.DATABASE_URL) {
pg.defaults.ssl = { rejectUnauthorized: false }
}
const sharedConfig = {
client: 'pg',
migrations: {directory: './data/migrations'},
seeds: {directory: './data/seeds'},
}
module.exports = {
development: {
...sharedConfig,
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
}
},
production: {
...sharedConfig,
connection: process.env.DATABASE_URL,
pool: { min: 2, max: 10 },
},
};
require('dotenv').config()
const pg = require('pg');
if (process.env.DATABASE_URL) {
pg.defaults.ssl = { rejectUnauthorized: false }
}
DATABASE_URL
environment variable. that's because this code snippet wont do anything in development but is necessary when we run this all on Heroku later where there is a DATABASE_URL
environment variable.const sharedConfig = {
client: 'pg',
migrations: {directory: './data/migrations'},
seeds: {directory: './data/seeds'},
}
sharedConfig
variable is because those config variables are shared between our development and production environments. It saves us some typing down here in the last piece of code.module.exports = {
development: {
...sharedConfig,
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
}
},
production: {
...sharedConfig,
connection: process.env.DATABASE_URL,
pool: { min: 2, max: 10 },
},
};
...sharedConfig
is our variable from before setting the client, migration, and seed configurations. then we have a connection
variable. connection
tells knex where the database lives and creates a connection with the database server allowing us to populate it with data and interact with it using our code. The last unexplained bit is this.pool: { min: 2, max: 10 }
knexfile.js
and it should look like this now.knex migrate:make first-migration
knex seed:make 001_first-seed
knexfile.js
where we did this?const sharedConfig = {
client: 'pg',
migrations: {directory: './data/migrations'},
seeds: {directory: './data/seeds'},
}
exports.up = (knex) => {
return knex.schema
.createTable('profiles', function (table) {
table.increments('profile_id');
table.string('name', 128).notNullable();
});
};
exports.down = (knex) => {
return knex.schema.dropTableIfExists('profiles');
};
const profiles = [
{
name: 'John'
},
{
name: 'Abigail'
},
{
name: 'Patty'
},
{
name: 'Sally'
},
{
name: 'Gary'
}
];
exports.seed = function (knex) {
return knex('profiles').del()
.then(() => {
return knex('profiles').insert(profiles)
})
};
knex migrate:latest
knex seed:run
Databases
and click refresh. You should now be able to expand your database, then schemas, then tables, to see your newly created database tables. It should look like thisprofiles
and click view/edit data
and then click all rows
to view your seed data in your table.git add .
git commit -m 'second commit'
git push
new
button in the top right corner. I create a new app using the new
button in the top right and click create new app
.git push heroku main
heroku postgres
. more
in the top right, and click run console
to open a console command box. Where it says bash you run your knex migrate:latest
and knex seed:run
commands. This will migrate and seed your Heroku database.data
directory create a file called db-config.js
and paste this code.require('dotenv').config();
const knex = require('knex');
const dbEnvironment = process.env.NODE_ENV || 'development';
const configs = require('../../knexfile')[dbEnvironment]
module.exports = knex(configs)
dbEnvironment
and then uses our configuration from our knexfile.js
for that environment and sets it to a configs
variable. We are using either development or production in this project. Then it exposes that database configuration so that our code can query the correct database and preform basic operations within our app.model.js
and route.js
file at the root of the project. Normally I would put model and route files within an API
folder but for the sake of speed and simplicity I will put them in the main project folder. Open the newly created model.js
and add this code.const db = require('./data/db-config');
const findAll = () => {
return db('profiles')
}
module.exports = {
findAll
}
findAll
that returns all entries of the profiles table we created. Lastly we export the model function so our routes can use it. route.js
file and add a basic route to return this database information.const router = require('express').Router()
const Profiles = require('./model')
router.get('/', async (req, res) => {
const profiles = await Profiles.findAll()
res.json(profiles)
})
module.exports = router
db-config.js
, model.js
, and route.js
all set up, the last thing to do is connect it to your index.js
file and test itindex.js
to make this work.const testRouter = require('./route')
route.js
file we just worked on.server.use('/test', testRouter)
index.js
look like this when its properly updated.http://localhost:5000
. To access the data using the new code we just wrote, add your /test route at the end of the URL. http://localhost:5000/test
. If done correctly your web browser should now be showing you the information from your database.git add .
git commit -m 'last commit'
git push
git push heroku main