الجزء الثاني من الـExpressJS Templating Using Pug

AbdullaScriptمنذ 6 سنوات

السلام عليكم و رحمة الله و بركاته ..

عودة الى الجزء الاول، وضحت كيفية ارسال بيانات من تطبيق الNode الى Pug وكيفية استقبال البيانات في الطرف الاخر و عرضها.

 

في هذا الدرس سنتعامل مع قاعدة البيانات ونرسل البيانات بطريقتين مختلفتين:

  1. سيتم ارسال جميع البيانات من احد الجداول الى الواجهة و سأعرض لكم طريقة التعامل مع هذا النوع من البيانات المرسله
  2. سننشأه items عباره عن json objects  وبعدها نرسلهم.

 

الطريقة الأولى:

و بالحديث عن قواعد البيانات، سنستخدم قاعدة بيانات MySQL هذه المره ( الرجاء الرجوع للدرس الاول للحصول على كافة التجهيزات لهذا الدرس). / هنا , انشأ قاعدة بيانات بإسم company وجدول employees مثلا  ومن ثم اضف هذه المدخلات.


-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 09, 2017 at 10:41 AM
-- Server version: 5.7.18-0ubuntu0.16.04.1
-- PHP Version: 7.1.5-1+deb.sury.org~xenial+2

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `company`
--

-- --------------------------------------------------------

--
-- Table structure for table `employees`
--

CREATE TABLE `employees` (
  `ID` int(11) NOT NULL,
  `name` text COLLATE utf8_unicode_ci NOT NULL,
  `position` text COLLATE utf8_unicode_ci NOT NULL,
  `office` text COLLATE utf8_unicode_ci NOT NULL,
  `age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `employees`
--

INSERT INTO `employees` (`ID`, `name`, `position`, `office`, `age`) VALUES
(1, 'Airi Satou', 'Accountant', 'Tokyo', 23),
(2, 'Airi Satou', 'Accountant', 'Tokyo', 23),
(3, 'Donna Snider', 'Customer Support', 'New York', 27),
(4, 'Brenden Wagner', 'Software Engineer', 'San Francisco', 28),
(5, 'Caesar Vance', 'Pre-Sales Support', 'New York', 23),
(6, 'Cedric Kelly', 'Senior Javascript Developer', 'Edinburgh', 22),
(7, 'Dai Rios', 'Personnel Lead', 'Edinburgh', 35);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `employees`
--
ALTER TABLE `employees`
  ADD PRIMARY KEY (`ID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `employees`
--
ALTER TABLE `employees`
  MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

 

افتح ملف app.js و انشأ هذا الاوبجكت لعمل connection بين التطبيق وقاعدة البيانات


// connection
var connection = mysql.createConnection({
 host     : 'localhost',
 user     : '...',
 password : '...',
 database : 'db_name'
});

 

بعد ذلك،  سنقوم بتعديل صفحة الـdetails في ملف app.js  - المسار الذي يعرض صفحة الـdetails  -  لعمل Selection query


app.get('/details', function(req, res) {

connection.query('SELECT * From `employees`', function (error, results, fields) {
 if (error) throw error;
 console.log('The solution is: ', results);

  res.render('details', {
    title: 'Details - Pug ExpressJS NodeJS Tutorial',
    employees: results
  });

});
  

});

الـsyntax بسيط جدا، اولا connection وهو متغير التوصيل مم ثم query ثابته بعد ذلك الكويري  ومن ثم الارقيومنتس (لمعلومات اكثر تجدونها هنا https://github.com/mysqljs/mysql/blob/master/Readme.md )

 

مخرجات اي query دائما ما يكون json object بالتالي متغير results هو عباره عن list of objects


[
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
]

 

نرجع إلى ملف details.pug ونقوم بتعديل block الجدول إلى التالي


      table#example.display.nowrap.dataTable.dtr-inline.collapsed(cellspacing='0')
        thead
          tr(role='row')
            th.sorting(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Name: activate to sort column ascending', style='width: 142px;') Name
            th.sorting(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Position: activate to sort column ascending', style='width: 192px;') Position
            th.sorting(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Office: activate to sort column ascending', style='width: 89px;') Office
            th.dt-body-right.sorting_asc(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Age: activate to sort column descending', style='width: 37px;', aria-sort='ascending') Age
        tfoot
          tr
            th(rowspan='1', colspan='1') Name
            th(rowspan='1', colspan='1') Position
            th(rowspan='1', colspan='1') Office
            th.dt-body-right(rowspan='1', colspan='1') Age
        tbody
        for employee in employees
          tr.odd(role='row')
            td #{employee.name}
            td #{employee.position}
            td #{employee.office}
            td.dt-body-right.sorting_1 #{employee.age}

 

نلاحظ وجود الـfor loop و طريقة استقبال وعرض المعلومات بسطر واحد فقط و ترجمته حرفيا ان لكل موظف في اوبجكت الموظفين ( الذي ارسلناه من الـNode ) قم بعمل صف في الجدول واضف مابعده


        for employee in employees
          tr.odd(role='row')
            td #{employee.name}
            td #{employee.position}
            td #{employee.office}
            td.dt-body-right.sorting_1 #{employee.age}

 

بهذا انتهينا من الجزء الأول للدرس وننتقل للجزء الثاني:

هذا الجزء من الدرس يتعلق بكيفية عمل items بشكل تخصيصي .. ان ماذا لو انك لا تريد ان تضم عمر الموظف في جدول العرض؟ سنقوم بالتالي في ملف app.js و details.pug - وكلشئ آخر يبقى كما هو:


//app.js
app.get('/details', function (req, res) {

    connection.query('SELECT * From `employees`', function (error, results, fields) {
        if (error) {
            throw error;
        } else {
            console.log('The solution is: ', results);
            var employees_json = [];
            for (var index = 0; index < results.length; index++) {
                
                var item = {
                    name: results[index].name,
                    position: results[index].position,
                    office: results[index].office
                }
                employees_json.push(item);
            }

            res.render('details', {
                title: 'Details - Pug ExpressJS NodeJS Tutorial',
                employees: employees_json
            });
        }

    });

});

//details.pug
      table#example.display.nowrap.dataTable.dtr-inline.collapsed(cellspacing='0')
        thead
          tr(role='row')
            th.sorting(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Name: activate to sort column ascending', style='width: 142px;') Name
            th.sorting(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Position: activate to sort column ascending', style='width: 192px;') Position
            th.sorting(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Office: activate to sort column ascending', style='width: 89px;') Office
            //th.dt-body-right.sorting_asc(tabindex='0', aria-controls='example', rowspan='1', colspan='1', aria-label='Age: activate to sort column descending', style='width: 37px;', aria-sort='ascending') Age
        tfoot
          tr
            th(rowspan='1', colspan='1') Name
            th(rowspan='1', colspan='1') Position
            th(rowspan='1', colspan='1') Office
            th.dt-body-right(rowspan='1', colspan='1') Age
        tbody
        for employee in employees
          tr.odd(role='row')
            td #{employee.name}
            td #{employee.position}
            td #{employee.office}
            //td.dt-body-right.sorting_1 #{employee.age}

 

 

إضغط هنا لتحميل ملفات الدرس الثاني anwbh-app-lesson2.zip

كلمات دليلية:
1
إعجاب
1603
مشاهدات
0
مشاركة
0
متابع
متميز
محتوى رهيب

التعليقات (0)

لايوجد لديك حساب في عالم البرمجة؟

تحب تنضم لعالم البرمجة؟ وتنشئ عالمك الخاص، تنشر المقالات، الدورات، تشارك المبرمجين وتساعد الآخرين، اشترك الآن بخطوات يسيرة !