In this project, we will go over how to use massive with a node server to connect to a postgres database.
- Run
npm install. - Review the
index.jsfile to get familiar with it.
In this step, we'll install massive into our project and require it in index.js.
- Run
npm install massive dotenv - Require and configure
dotenvat the top of the file. - Require
massiveunderneathexpress.
index.js
require("dotenv").config();
const express = require("express");
const massive = require("massive");
const app = express();
const { SERVER_PORT } = process.env;
app.use(express.json());
app.listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});In this step, we'll connect SQLTabs to our Heroku database. We'll then add a new table to our Heroku database called airplanes.
- Open SQLTabs.
- Connect to your Heroku database with SQLTabs by using the URI connection string.
- Create the following
airplanestable:-
CREATE TABLE airplanesCREATE TABLE airplanes ( plane_id SERIAL NOT NULL, plane_type varchar(40) NOT NULL, passenger_count integer NOT NULL );
-
In this step, we'll establish a connection to our database using massive in index.js.
- Create a file named
.env- Make sure to add
.envto your.gitignore
- Make sure to add
- Open your
.envand add a variable namedSERVER_PORTand set it to 3000. - Add a variable named
CONNECTION_STRINGthat equals the URI connection string from your Heroku database.- There should be no quotes around the connection string.
- Open
index.js. - Destructure
CONNECTION_STRINGoff ofprocess.env. - Invoke massive and pass in a configuration object containing our connection string which we can access through the
CONNECTION_STRINGvariable. This configuration object should also contain a nested object called ssl with one property,rejectUnauthorizedset to false. By passing in this configuration object, massive will return a promise. Chain a.thenthat has one parameter calleddbInstanceand then returnsapp.set('db', dbInstance). This will give our express application access to our database.
.env
SERVER_PORT=3000
CONNECTION_STRING=postgres://username:password@host/dbname
index.js
require("dotenv").config();
const express = require("express");
const massive = require("massive");
const app = express();
const { SERVER_PORT, CONNECTION_STRING } = process.env;
massive({
connectionString: CONNECTION_STRING,
ssl: {
rejectUnauthorized: false
}
}).then(dbInstance => app.set("db", dbInstance));
app.use(express.json());
app.listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});In this step, we will add some seed data to our database using the the files already created in the db folder.
- Open
index.js. - Modify the massive
.thento setdbon app and also calldbInstance.new_planes.- Chain a
.thenthat has a parameter calledplanes. Return aconsole.logofplanes. - Chain a
.catchthat has a parameter callederr. Return aconsole.logoferr.
- Chain a
- Restart/Run the API so the planes get added to the table.
- Comment out
dbInstance.new_planesso we don't get duplicate planes.
index.js
require("dotenv").config();
const express = require("express");
const massive = require("massive");
const app = express();
const { SERVER_PORT, CONNECTION_STRING } = process.env;
massive(CONNECTION_STRING).then(dbInstance =>{
app.set('db', dbInstance);
// dbInstance.new_planes()
// .then( planes => console.log( planes ) )
// .catch( err => console.log( err ) );
});
app.use(express.json());
app.listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});- Open
index.js. - Underneath the comment of
new_planes, calldbInstance.get_planes.- Chain a
.thenthat has a parameter calledplanes. Return aconsole.logofplanes. - Chain a
.catchthat has a parameter callederr. Return aconsole.logoferr.
- Chain a
index.js
require("dotenv").config();
const express = require("express");
const massive = require("massive");
const app = express();
const { SERVER_PORT, CONNECTION_STRING } = process.env;
massive(CONNECTION_STRING).then(dbInstance => {
app.set("db", dbInstance);
// dbInstance.new_planes()
// .then( planes => console.log( planes ) )
// .catch( err => console.log( err ) );
dbInstance.get_planes()
.then(planes => console.log(planes))
.catch(err => console.log(err));
});
app.use(express.json());
app.listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});In this step, we will use our dbInstance in a controller file instead of in index.js.
- Open
controller.js. - Use
module.exportsto export an object. - Add a
getPlanesproperty to the object that equals a function with areq,res, andnextparameter. - Get the
dbInstanceby usingreq.app.get('db'). - Using the
dbInstacecallget_planes.- Chain a
.thenwith a parameter calledplanes. Then useresto send backplanesand a status of 200. - Chain a
.catchwith a parameter callederr. Console log theerrand useresto send a status 500.
- Chain a
- Open
index.js. - Require
controller.js. - Create a
GETendpoint on/api/planesthat callscontroller.getPlanes. - In your index.js file, comment out dbInstance.get_planes as this is now setup in the controller.
controller.js
module.exports = {
getPlanes: (req, res, next) => {
const dbInstance = req.app.get("db");
dbInstance.get_planes()
.then(planes => {
res.status(200).send(planes);
})
.catch(err => {
console.log(err);
res.status(500).send(err);
});
}
}; index.js
require("dotenv").config();
const express = require("express");
const massive = require("massive");
const controller = require("./controller");
const app = express();
const { SERVER_PORT, CONNECTION_STRING } = process.env;
massive(CONNECTION_STRING).then(dbInstance => {
app.set("db", dbInstance);
// dbInstance.new_planes()
// .then( planes => console.log( planes ) )
// .catch( err => console.log( err ) );
// dbInstance.get_planes()
// .then(planes => console.log(planes))
// .catch(err => console.log(err));
});
app.use(express.json());
app.get("/api/planes", controller.getPlanes);
app.listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});In this step, we'll modify the get_planes SQL file to use a parameter.
- Open
get_planes.sql. - At the end of the first line, add
WHERE passenger_count > $1; - Open
controller.js. - Pass in an array as the first parameter for
dbInstance.get_planes.- Use number
25as the first element of the array.
- Use number
get_planes.sql
SELECT * FROM airplanes WHERE passenger_count > $1; controller.js
module.exports = {
getPlanes: (req, res, next) => {
const dbInstance = req.app.get("db");
dbInstance.get_planes([25])
.then(planes => {
res.status(200).send(planes);
})
.catch(err => {
console.log(err);
res.status(500).send(err);
});
}
};If you see a problem or a typo, please fork, make the necessary changes, and create a pull request so we can review your changes and merge them into the master repo and branch.
© DevMountain LLC, 2017. Unauthorized use and/or duplication of this material without express and written permission from DevMountain, LLC is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to DevMountain with appropriate and specific direction to the original content.
