Build A Photo Gallery app with Ionic2, Cloudinary, NodeJs And MongoDB part 2


In part 1 we created the client app (Ionic 2 App), in this part we will focus on building the NodeJS API.

I assume that you are familiar with creating NodeJS App as am not going to go into details about how to create a NodeJS API.

The NodeJS API will be deployed to Heroku. The images will be uploaded to Cloudinary  server, and the MongoDB hosted in MLab.




Am not going to go into details about Heroku, Cloudinary, and MLab, you can read more about them in their respective websites.

Project Structure and Dependencies

Since our API is written with NodeJS, the first thing is to create our project directory and add package.json  where will add all our API dependencies.

The package.json should look like so:

{
  "name": "photocloud",
  "version": "1.0.0",
  "description": "A nodejs app to upload image to cloudinary",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [
    "cloudinary",
    "nodejs",
    "api",
    "heroku",
    "mongodb",
    "photo-upload"
  ],
  "author": "Mark Adesina",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.15.2",
    "cloudinary": "^1.4.4",
    "connect-multiparty": "^2.0.0",
    "cors": "^2.8.1",
    "express": "^4.14.0",
    "mongoose": "^4.6.6"
  },
  "engines": {
    "node": "6.0.0"
  }
}



There is nothing too complex about the package.json file. But our main concern here is the dependencies.  The dependencies we will require for this API are:

We won't be talking much about these dependencies. The only one among them that we can talk about is the cloudinarys' which is just a cloudinary nodejs sdk. You can read more about it here.

You can install the dependencies by running:

npm install


To have an overview of the project, it is always a good idea to present a directory structure of the app:



Now, we will setup our server. Open the file named app.js located in the root of server folder and paste the code below. This is the entry point into our node application.


var express     =   require('express'),
    app         =   express(),
    bodyParser  =   require('body-parser'),
    cors        =   require('cors'),
    config      =   require('./config/settings'),
    db          =   require('./db/db');
    server      =   require('http').createServer(app);    


app.set('port', (process.env.PORT || config.serverPort));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

require('./route/route')(express,app);


server.listen(app.get('port'), function() {
 console.log('Node app is running on port', app.get('port'));
});

This tutorial is not aimed at teaching NodeJS application, so I wont explain some of the content of the files that we have here. The source code will be available on my github page.

Accessing Cloudinary API SDKs

Create a free account on cloudinary website.

The dashboard shows a list of SDKs that you can use to talk to Cloudinary in most of the popular languages including Node.js.

Cloudinary core exposes APIs based on your cloud name and all these SDKs do is serve as a language wrapper to these URL. So instead of littering your app with these URLs, you have a better intuitive language based method APIs to work with.

The cloud name is not your name but the name you chose when signing up as cloud name. There three things you need to take note of in your dashboard they are your Cloud Name, API Key, and API Secret.

Handling Image Upload

We will cover how you can upload your images to cloudinary server. First update the settings.js located in the config folder of your NodeJS App like so:
module.exports = {
    'serverPort':5000,
    'dbUrl':'mongodb://dbuser:dbpassword@ds143737.mlab.com:43737/dbname',
    'cloud_name': 'YOUR_CLOUD_NAME',
    'api_key': 'YOUR_API_KEY',
    'api_secret': 'YOUR_API_KEY_SECRET'

}

Replace the dbUrl to reflect your MongoDb url as found in MLab when you created yours, your cloud_name, api_key and api_secret should also reflect yours as found in your cloudinary server Dashboard. So let's see how we can upload images to the cloud using the cloudinary NodeJS SDK we have installed. Paste the code below in post.js located in controller folder in the nodejs app. /controller/post.js
var Post = require('../models/post');
var config = require('../config/settings'),
    cloudinary = require('cloudinary');
var multipart = require('connect-multiparty')();

cloudinary.config({
    cloud_name: config.cloud_name,
    api_key: config.api_key,
    api_secret: config.api_secret
});

module.exports = {

    upload: function (req, res, next) {
        
        cloudinary.uploader.upload(req.files.file.path, function (resp) {

            var newPost = new Post({
                title: req.body.title,
                image_url: resp.url,
                description: req.body.description
            }).save(function (err, response) {
                if (err) return next(err);
                res.json({
                    error: false,
                    result: response
                });
            })

        });

    },
    get: function (req, res, next) {
        Post.find({}, function (err, result) {
            if(err) return next(err);
            res.json({posts:result});
        });
    }

}

First we required our mongoose model which we have in /models/post.js, config,multipart and cloudinary, then we configured Cloudinary using our credentials available on the dashboard via the config. Once the upload route is hit, we upload the file to Cloudinary server using the SDK's cloudinary.uploader.upload API and persist the post body including the URL returned from Cloudinary to the MongoDB using Monoose. One thing to notice is the file keyword in the req.files.file.path, if you remember in our ionic app where we used filetransfer pluging we have the plugin option like so:

 let options = {
      fileKey: "file",
      fileName: filename,
      chunkedMode: false,
      mimeType: "image/jpg",
      params: { 'title': this.postTitle, 'description': this.desc }
    };

You can see that the fileKey value is file, that is why we now have the file keyword to access the incoming file within our NodeJS App.

Deployment App to Heroku

You can read this article on how to deploy the app to heroku server.

The full source code can found here.

Your comments are welcome. Happy Coding.

No comments

Powered by Blogger.