4 Mart 2015 Çarşamba

Node.js, Express ve MongoDB ile basit bir RESTful web servis yazma

Node yüklü değilse yükleyin.
C:\node klasörü açın.

Express yoksa yükleyin. Varsa update edin:
npm update -g express
npm update -g express-generator

Son olarak bir proje klasörü yaratın:
express nodetest2

oluşan package.json dosyasına ilave yapalım:
"jade": "*",
        "mongodb": "*",
        "mongoskin": "*"

proje klasörüne girelim. dependencyleri yükleyelim:
npm install

proje klasörü içine veritabanı için bir klasör açalım:
mkdir data

views klasöründe layout.jade açalım. İlave edelim:
script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
        script(src='/javascripts/global.js')

/public/stylesheets/style.css üzerine şuradaki içeriği kopyalayalım:
http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/style.css

views klasöründe index.jade i açalım. Şöyle değiştirelim:
extends layout

block content
    h1= title
    p Welcome to our test

    // Wrapper
    #wrapper

        // USER LIST
        h2 User List
        #userList
            table
                thead
                    th UserName
                    th Email
                    th Delete?
                tbody
        // /USER LIST

    // /WRAPPER

Konsola dönüp node serveri başlatalım:
C:\node\nodetest2\> npm start

http://localhost:3000 açtığımızda basit bir sayfa görürüz.

Mongo daemonu çalıştıralım:
C:\mongo\> mongod --dbpath c:\node\nodetest2\data

Yeni bir konsol açıp Mongoya bağlanalım:
C:\mongo\>mongo

Mongo konsolundan yeni bir db yaratalım:
use nodetest2

Kullanıcı listesi ekleyelim:
db.userlist.insert({'username' : 'test1','email' : 'test1@test.com','fullname' : 'Bob Smith','age' : 27,'location' : 'San Francisco','gender' : 'Male'})

C:\node\nodetest2\app.js açalım. bodyParser ın hemen altına ekleyelim:
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/nodetest2", {native_parser:true});

Sonra app.use('/', routes); satırının hemen üzerine ekleyelim:
// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

C:\node\nodetest2\routes\users.js açalım. 
/* GET users listing. */
router.get('/', function(req, res) {
  res.send('respond with a resource');
});
Bu kısmı silip yerine yazalım:
/*
 * GET userlist.
 */
router.get('/userlist', function(req, res) {
    var db = req.db;
    db.collection('userlist').find().toArray(function (err, items) {
        res.json(items);
    });
});

Node serveri yeniden başlatalım:
C:\node\nodetest2\> npm start

http://localhost:3000/users/userlist açalım. Tek bir kayıt görürüz.

/nodetest2/public/javascripts/global.js dosyası yaratalım ve içeriği yazalım:
// Userlist data array for filling in info box
var userListData = [];

// DOM Ready =============================================================
$(document).ready(function() {

    // Populate the user table on initial page load
    populateTable();

});

// Functions =============================================================

// Fill table with data
function populateTable() {

    // Empty content string
    var tableContent = '';

    // jQuery AJAX call for JSON
    $.getJSON( '/users/userlist', function( data ) {

        // For each item in our JSON, add a table row and cells to the content string
        $.each(data, function(){
            tableContent += '<tr>';
            tableContent += '<td><a href="#" class="linkshowuser" rel="' + this.username + '">' + this.username + '</a></td>';
            tableContent += '<td>' + this.email + '</td>';
            tableContent += '<td><a href="#" class="linkdeleteuser" rel="' + this._id + '">delete</a></td>';
            tableContent += '</tr>';
        });

        // Inject the whole content string into our existing HTML table
        $('#userList table tbody').html(tableContent);
    });
};

http://localhost:3000/ açalım ve tabloda kaydın çıktığını görelim.

C:\node\nodetest2\public\javascripts\global.js dosyasını açalım.
// jQuery AJAX call for JSON
    $.getJSON( '/users/userlist', function( data ) {
Satırının hemen altına ekleyelim:
  // Stick our user data array into a userlist variable in the global object
    userListData = data;

 Yine global.js in en sonuna ekleyelim:
// Show User Info
function showUserInfo(event) {

    // Prevent Link from Firing
    event.preventDefault();

    // Retrieve username from link rel attribute
    var thisUserName = $(this).attr('rel');

    // Get Index of object based on id value
    var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);

// Get our User Object
    var thisUserObject = userListData[arrayPosition];

    //Populate Info Box
    $('#userInfoName').text(thisUserObject.fullname);
    $('#userInfoAge').text(thisUserObject.age);
    $('#userInfoGender').text(thisUserObject.gender);
    $('#userInfoLocation').text(thisUserObject.location);

};

Aynı dosyada DOM Ready kısmında tabloyu doldurmadan hemen öncesine ekleyelim:
// Username link click
    $('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);

C:\node\nodetest2\views\index.jade açalım. 
#wrapper satırından hemen sonra ekleyelim:
 // USER INFO
        #userInfo
            h2 User Info
            p
                strong Name:
                |  <span id='userInfoName'></span>
                br
                strong Age:
                |  <span id='userInfoAge'></span>
                br
                strong Gender:
                |  <span id='userInfoGender'></span>
                br
                strong Location:
                |  <span id='userInfoLocation'></span>
        // /USER INFO


http://localhost:3000 açalım. 
kullanıcı adına tıklayınca sol taraftaki kutuda bilgilerinin geldiğini görebiliriz.

/views/index.jade açalım. user list in hemen altına ekleyelim:
// ADD USER
        h2 Add User
        #addUser
            fieldset
                input#inputUserName(type='text', placeholder='Username')
                input#inputUserEmail(type='text', placeholder='Email')
                br
                input#inputUserFullname(type='text', placeholder='Full Name')
                input#inputUserAge(type='text', placeholder='Age')
                br
                input#inputUserLocation(type='text', placeholder='Location')
                input#inputUserGender(type='text', placeholder='gender')
                br
                button#btnAddUser Add User
        // /ADD USER

Artık index.jade son halini şu şekilde almış olmalı:
extends layout

block content
    h1= title
    p Welcome to our test

    // Wrapper
    #wrapper

        // USER INFO
        #userInfo
            h2 User Info
            p
                strong Name:
                |  <span id='userInfoName'></span>
                br
                strong Age:
                |  <span id='userInfoAge'></span>
                br
                strong Gender:
                |  <span id='userInfoGender'></span>
                br
                strong Location:
                |  <span id='userInfoLocation'></span>
        // /USER INFO

        // USER LIST
        h2 User List
        #userList
            table
                thead
                    th UserName
                    th Email
                    th Delete?
                tbody
        // /USER LIST

        // ADD USER
        h2 Add User
        #addUser
            fieldset
                input#inputUserName(type='text', placeholder='Username')
                input#inputUserEmail(type='text', placeholder='Email')
                br
                input#inputUserFullname(type='text', placeholder='Full Name')
                input#inputUserAge(type='text', placeholder='Age')
                br
                input#inputUserLocation(type='text', placeholder='Location')
                input#inputUserGender(type='text', placeholder='gender')
                br
                button#btnAddUser Add User
        // /ADD USER

    // /WRAPPER

C:\node\nodetest2\routes\users.js açalım.
module.exports tan hemen önce ekleyelim:
/*
 * POST to adduser.
 */
router.post('/adduser', function(req, res) {
    var db = req.db;
    db.collection('userlist').insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

C:\node\nodetest2\public\javascripts\global.js açalım.
DOM Ready kısmında user list name click in hemen altına ekleyelim:
// Add User button click
    $('#btnAddUser').on('click', addUser);

global.js in sonuna ekleyelim:
// Add User
function addUser(event) {
    event.preventDefault();

    // Super basic validation - increase errorCount variable if any fields are blank
    var errorCount = 0;
    $('#addUser input').each(function(index, val) {
        if($(this).val() === '') { errorCount++; }
    });

    // Check and make sure errorCount's still at zero
    if(errorCount === 0) {

        // If it is, compile all user info into one object
        var newUser = {
            'username': $('#addUser fieldset input#inputUserName').val(),
            'email': $('#addUser fieldset input#inputUserEmail').val(),
            'fullname': $('#addUser fieldset input#inputUserFullname').val(),
            'age': $('#addUser fieldset input#inputUserAge').val(),
            'location': $('#addUser fieldset input#inputUserLocation').val(),
            'gender': $('#addUser fieldset input#inputUserGender').val()
        }

        // Use AJAX to post the object to our adduser service
        $.ajax({
            type: 'POST',
            data: newUser,
            url: '/users/adduser',
            dataType: 'JSON'
        }).done(function( response ) {

            // Check for successful (blank) response
            if (response.msg === '') {

                // Clear the form inputs
                $('#addUser fieldset input').val('');

                // Update the table
                populateTable();

            }
            else {

                // If something goes wrong, alert the error message that our service returned
                alert('Error: ' + response.msg);

            }
        });
    }
    else {
        // If errorCount is more than 0, error out
        alert('Please fill in all fields');
        return false;
    }
};

Node serveri yeniden başlatalım.
http://localhost:3000 açtığımızda artık form çalışıyor olacaktır.
Yeni kullanıcılar ekleyip bilgilerini görebiliriz.

/routes/users.js açıp en altta module.exports tan hemen önce ekleyelim:
 /*
 * DELETE to deleteuser.
 */
router.delete('/deleteuser/:id', function(req, res) {
    var db = req.db;
    var userToDelete = req.params.id;
    db.collection('userlist').removeById(userToDelete, function(err, result) {
        res.send((result === 1) ? { msg: '' } : { msg:'error: ' + err });
    });
});

global.js de DOM Ready kısmına ekleyelim:
// Delete User link click
    $('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);


global.js en sonuna ekleyelim:
// Delete User
function deleteUser(event) {

    event.preventDefault();

    // Pop up a confirmation dialog
    var confirmation = confirm('Are you sure you want to delete this user?');

    // Check and make sure the user confirmed
    if (confirmation === true) {

        // If they did, do our delete
        $.ajax({
            type: 'DELETE',
            url: '/users/deleteuser/' + $(this).attr('rel')
        }).done(function( response ) {

            // Check for a successful (blank) response
            if (response.msg === '') {
            }
            else {
                alert('Error: ' + response.msg);
            }

            // Update the table
            populateTable();

        });

    }
    else {

        // If they said no to the confirm, do nothing
        return false;

    }

};

Node serveri yeniden başlatalım.
http://localhost:3000 açtığımızda artık kayıtları silme işlemi de yapabiliyoruz.

 
(Kaynak: http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/)


Hiç yorum yok:

Yorum Gönder