วันอาทิตย์ที่ 13 พฤษภาคม พ.ศ. 2561

Commit 11 Nodejs Wordbucket : can add word with explanation

Nodejs : Wordbucket GitHub Link

Commit 11 Nodejs Wordbucket : can add word with explanation

Commits on May 1, 2018

index.js

- เนื่องจากใน model node version ที่ใช้ไม่สามารถใช้ association จาก model ได้ ต้องสร้าง association จากใน index.js "const Explanation_Word = Explanation.belongsTo(Word, {as: 'Explanation_Word'});"
- สร้างตัวแปร message ได้เก็บ message ที่จะเตือน user เมื่อพยายาม add duplicate / ช่องว่าง ลงใน database
- update function addingNewWord() ให้ add explanation พร้อม word ได้เหมือนใน django โดยถ้า add duplicate / ช่องว่าง จะไม่ add ลงใน database
- เพิ่ม function renderDisplayWithMessage ไว้ render index.ejs พร้อม message (เพราะ ถ้าใส่ในหน้าเดิมเมื่อ refresh message จะยังอยู่ ไม่หายไปเหมือน django) จึงเขียนกันไว้
- เพิ่ม function view_word() เพื่อดู explanation ของ word นั้นๆ

114  index.js

@@ -1,65 +1,119 @@
+//------------------------- setting and import -------------------------
var express = require('express'); //require the just installed express app
var app = express(); //then we call express
var db = require('./models');
var Word = db.Word;
-var Explan = db.Explanation;
+var Explanation = db.Explanation;
+
+const Explanation_Word = Explanation.belongsTo(Word, {as: 'Explanation_Word'});
+//Word.Explanation = Word.hasMany(Explanation);
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
+var message = "";
+
app.set('view engine', 'ejs'); //template
-var complete = [];
+//------------------------- functions -------------------------
-//function
-function addingNewWord (req, res) { //post route for adding new word
- //var newWord = req.body.word_input;
- //word.push(newWord);
- Word.create({
- word: req.body.word_input,
- }); //add the new word from the post route into the array
+function addingNewWord (req, res, next) { //post route for adding new word
+ var word_ref = req.body.word_input
+ var explanation_ref = req.body.explanation_input
+ if(word_ref == "" && explanation_ref == ""){
+ message = "Please enter the word.";
+ return res.redirect("/message");
+ }
+ else if (word_ref != "" && explanation_ref == ""){
+ message = ""
+ Word.create({
+ word: req.body.word_input,
+ }); //add the new word from the post route into the array
+ }
+ else if (word_ref != "" && explanation_ref != ""){
+ message = ""
+ Explanation.create({
+ Explanation_Word: {
+ word: req.body.word_input,
+ },
+ explanation_text: req.body.explanation_input,
+ like: 0,
+ dislike: 0,
+ }, {
+ include: [ Explanation_Word ]
+ });
+ }
res.redirect("/"); //after adding to the array go back to the root route
}
-function renderDisplay(req, res) { //render the ejs and display added word
+function renderDisplayWithMessage(req, res) { //render the ejs and display added word
Word.findAll({
- attributes: ['word'],
+ attributes: ['id','word'],
raw : true
}).then(function(query) {
var word = [];
+ var id = [];
query.forEach(function(item) {
word.push(item.word);
+ id.push(item.id);
});
- res.render("index", { word: word, complete: complete });
+ res.render("index", { word: word , id: id , message: message });
});
}
-// call function
-
-app.post('/addword', addingNewWord); //call function add word
+function renderDisplay(req, res) { //render the ejs and display added word
+ message = ""
+ Word.findAll({
+ attributes: ['id','word'],
+ raw : true
+ }).then(function(query) {
+ var word = [];
+ var id = [];
+ query.forEach(function(item) {
+ word.push(item.word);
+ id.push(item.id);
+ });
+ res.render("index", { word: word , id: id , message: message });
+ });
+}
+function view_word(req, res) { //view word detail
+ var wordID_ref = Number(req.params.id)
+ Word.findById(wordID_ref).then(function(query) {
+ var word = query.word;
+ var ExplanationWordId_ref = Number(query.id)
+ Explanation.findAll({
+ where: {
+ ExplanationWordId: ExplanationWordId_ref
+ },
+ attributes: ['explanation_text','like','dislike'],
+ raw : true
+ }).then(function(ref) {
+ var explanation = [];
+ var like = [];
+ var dislike = [];
+ ref.forEach(function(item) {
+ explanation.push(item.explanation_text);
+ like.push(item.like);
+ dislike.push(item.dislike);
+ });
+ res.render("detail", { word: word , explanation: explanation });
+ });
+ });
+}
-app.post("/removeword", function(req, res) {
- var completeWord = req.body.check;
-//check for the "typeof" the different completed word, then add into the complete word
- if (typeof completeWord === "string") {
- complete.push(completeWord);
+// ------------------------- call function -------------------------
-//check if the completed word already exist in the word when checked, then remove using the array splice method
- word.splice(word.indexOf(completeWord), 1);
+app.use('/addword', addingNewWord); //call function add word
- } else if (typeof completeWord === "object") {
- for (var i = 0; i < completeWord.length; i++) {
- complete.push(completeWord[i]);
- word.splice(word.indexOf(completeWord[i]), 1);
- }
- }
- res.redirect("/");
-});
+app.get("/message", renderDisplayWithMessage);
app.get("/", renderDisplay)
//the server is listening on port 3000 for connections
+
+app.get("/word/:id",view_word)
+
app.listen(3000, function () {
//db.sequelize.sync();
//console.log('Example app listening on port 3000!')

migrations/20180507184836-create-explanation.js

- เมื่อทำการ สร้าง association จากใน index.js "const Explanation_Word = Explanation.belongsTo(Word, {as: 'Explanation_Word'});" จะ auto สร้างตัวแปร foreign key ของความสัมพันธ์ one to many ในไฟล์ migration ของตาราง explanation จึงลบ entity word ทิ้ง ก่อน migration ใหม่

@@ -8,9 +8,9 @@ module.exports = {
primaryKey: true,
type: Sequelize.INTEGER
},
- word: {
- type: Sequelize.STRING,
- references: { model: 'Word', key: 'word' }
+ ExplanationWordId: {
+ type: Sequelize.INTEGER,
+ allowNull: false
},
explanation_text: {
allowNull: false,

models/explanation.js

- เพื่อใช้ ExplanationWordId จึงได้ทำการใส่ไว้ใน model และกำหนดความสัมพันธ์ไว้ข้างล่าง(ไม่อย่างนั้นจะ migrate ไม่ผ่านแต่ก็ยังต้องกำหนดความสัมพันธ์ไว้ใน index.js อยู่ดีถึงใช้ได้)

@@ -1,14 +1,14 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
var Explanation = sequelize.define('Explanation', {
- word: DataTypes.STRING,
+ ExplanationWordId: DataTypes.STRING,
explanation_text: DataTypes.STRING,
like: DataTypes.INTEGER,
dislike: DataTypes.INTEGER
}, {});
Explanation.associate = function(models) {
// associations can be defined here
- Explanation.belongsTo(models.Word);
+ Explanation.belongsTo(models.Word, { foreignKey: 'word' });
};
return Explanation;
};

views/detail.ejs

- สร้าง template detail ขึ้นเพื่อดู explanations ของ word นั้นๆโดยนำมาจาก project django มาดัดแปลงใช้ในรูปแบบของ ejs

@@ -0,0 +1,31 @@
+<html>
+
+ <head>
+ <title> WordBucket App </title>
+ <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet">
+ <link href="/styles.css" rel="stylesheet">
+ </head>
+
+<body>
+ <div class="container">
+
+ <h1>WordBucket App</h1>
+
+ <form action ="/addword" id="form1" method="POST">
+ <input name="explanation_input" id="id_new_eplanation" placeholder="Add explanation" />
+ </form>
+ <button type="submit" form="form1" value="Submit">Submit</button>
+
+ <h2><%= word %></h2>
+
+ <table id="id_word_table">
+ <% for( var i = 0; i < explanation.length; i++){ %>
+ <tr><td id="word.word">explanation <%= i+1 + " : " + explanation[i] %></td></tr>
+ <% } %>
+ </table>
+ <br><br><br>
+ <a href="/">home</a>
+</div>
+
+</body>
+</html>

views/index.ejs

- ลบการแสดงผลแบบเก่า ที่เพื่อนทำเหมือนใน To-Do app (link) เป็นในรูปแบบที่ทำใน project django แต่เปลี่ยนเป็นใช้รูปแบบของ ejs


@@ -9,27 +9,22 @@
<body>
<div class="container">
- <h1> A Simple WordBucket App </h1>
-
- <form action ="/addword" method="POST">
- <input name="word_input" id="id_new_word" placeholder="Add new word" />
- <input name="explanation_input" id="id_new_eplanation" placeholder="Add explanation" />
- <button> Add Word </button>
-
- <h2> Added Word </h2>
- <% word %>
- <% for( var i = 0; i < word.length; i++){ %>
- <li><input type="checkbox" name="check" value="<%= word[i] %>" /> <%= word[i] %> </li>
-
- <% } %>
-
- <button formaction="/removeword" type="submit"> Remove </button>
- </form>
-
- <h2> Completed word </h2>
- <% for(var i = 0; i < complete.length; i++){ %>
- <li><input type="checkbox" checked><%= complete[i] %> </li>
- <% } %>
+ <h1>WordBucket App</h1>
+
+ <h4><%= message %></h4>
+ <form action ="/addword" id="form1" method="POST">
+ <input name="word_input" id="id_new_word" placeholder="Add new word" />
+ <input name="explanation_input" id="id_new_eplanation" placeholder="Add explanation" />
+ </form>
+ <button type="submit" form="form1" value="Submit">Submit</button>
+
+
+ <table id="id_word_table">
+ <% for( var i = word.length-5; i < word.length; i++){ %>
+ <tr><td id="word.word"><a href="/word/<%= id[i] %>"><%= word[i] %></a></td></tr>
+ <% } %>
+ </table>
+
</div>


ไม่มีความคิดเห็น:

แสดงความคิดเห็น