I have written many articles on Node.js and AngularJs. In this article, I will demonstrate how to use PostgreSQL with Node.js and deploy on Heroku. I think you already smelled that this is one of starting article which will finally merged with Salesforce to create some cool application.
Assuming you already have some background knowledge on Node.js and Heroku, If not please visit previous articles of this blog or my Slideshare account. Using Angularjs is totally optional and you can use library like JQuery or plain JavaScript.
To connect PostgreSQL, we need “pg” module.
File -1 is code snippet of “package.json”. After creating this file, you will need to run command “npm install“. This command will install all the required dependencies needed for this application.
File 2, shows how different CRUD operations is performed in “pg” module of node.js. If you notice this file ; we are using “process.env.DATABASE_URL“. This variable will store Database string needed to connect PostgreSQL in heroku, this will be automatically available once you install “PostgreSQL” add-on in your Heroku application. If this variable is not available (like on local system) then we are using actual connection string of PostgreSQL installed on system. you will need to replace this connection string with your credentials.
If you want to create Table schema, you need to hit “/db/createTable” URL and if you want to delete table, hit “/db/dropTable” URL.
File 3 is Node.js starting file, which actually routes all requests. For code modularity, I have separated database operations related code in “File 2” and importing in this file.
File 4, is landing page which calls CRUD functions using ajax with the help of Angularjs.
File 5 – “App.json” which is important for “Heroku 1” button to work in Github. You can ignore this file. This file basically is used by Heroku to directly install this application on Heroku on single click and known as “Heroku Button“.
You can find complete code here on my Git repository and working demo here.
Please provide your feedback here, See you in next article.
Leave a Reply