Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adhiarta #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
21 changes: 21 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict'

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const home = require('./routers/home');
const menu = require('./routers/menu');
const restaurant = require('./routers/restaurant');


app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.set('views', './views')
app.set('view engine', 'ejs')

app.use('/', home)
app.use('/menus',menu)
app.use('/restaurants',restaurant)

app.listen(3000, console.log(`Ready.. Set.. GO!`))
9 changes: 9 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"development": {
"username": "adhiarta",
"password": null,
"database": "platinum_livecode4",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
16 changes: 16 additions & 0 deletions helpers/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function format_currency (number) {
reverse = number.toString().split('').reverse();
arr= [];
for(var i = 0; i<reverse.length;i++){
if((i+1) % 3 === 0 && (i+1) !== reverse.length){
arr.push(reverse[i]);
arr.push(',');
}else{
arr.push(reverse[i]);
}
}

return 'Rp. '+arr.reverse().join('');
}

module.exports = format_currency
30 changes: 30 additions & 0 deletions migrations/20180301021204-create-restaurant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Restaurants', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
address: {
type: Sequelize.STRING
},
createdAt: {
allowNull: true,
type: Sequelize.DATE
},
updatedAt: {
allowNull: true,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Restaurants');
}
};
39 changes: 39 additions & 0 deletions migrations/20180301021358-create-menu.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Menus', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
menu_type: {
type: Sequelize.STRING
},
rating: {
type: Sequelize.INTEGER
},
price: {
type: Sequelize.INTEGER
},
restaurantId: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Menus');
}
};
36 changes: 36 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};

if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
34 changes: 34 additions & 0 deletions models/menu.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
var Menu = sequelize.define('Menu', {
name: DataTypes.STRING,
menu_type: {
type : DataTypes.STRING,
validate : {
isIn: {
args : [['food', 'drink']],
msg : 'Isi form menu type dengan food / drink'
}
},
hooks : {
afterCreate : (menu, options) => {
if(menu.menu_type === 'food' && menu.price === 0) {
menu.price = 15000
} else if(menu.menu_type === 'drink' && menu.price === 0) {
menu.price = 10000
}
}
}
},
rating: DataTypes.INTEGER,
price: DataTypes.INTEGER,
restaurantId: DataTypes.INTEGER
}, {});
Menu.associate = function(models) {
// associations can be defined here
Menu.belongsTo(models.Restaurant, {
foreignKey: 'restaurantId'
})
};
return Menu;
};
14 changes: 14 additions & 0 deletions models/restaurant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
var Restaurant = sequelize.define('Restaurant', {
name: DataTypes.STRING,
address: DataTypes.STRING
}, {});
Restaurant.associate = function(models) {
// associations can be defined here
Restaurant.hasMany(models.Menu, {
foreignKey: 'restaurantId'
})
};
return Restaurant;
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "express-sequelize-final",
"version": "1.0.0",
"description": "",
"main": "index.js",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
Expand Down
9 changes: 9 additions & 0 deletions routers/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express')
const router = express.Router()


router.get('/', (req, res) => {
res.render('home')
})

module.exports = router;
96 changes: 96 additions & 0 deletions routers/menu.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const express = require('express')
const router = express.Router()
const Model = require('../models')
const Menu = Model.Menu
const Restaurant = Model.Restaurant
const format = require('../helpers/helper')


router.get('/', (req, res) => {
Menu.findAll({
include: [ Model.Restaurant ]
})
.then(menus => {
Restaurant.findAll()
.then(restaurants => {
res.render('menu', { menus, restaurants, error: null, format })
// res.send({ menus, restaurants, err: true, format })
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
})
})

router.post('/', (req, res) => {
let objMenu = req.body
console.log(objMenu);
Menu.create(objMenu)
.then(() => {
res.redirect('/menus')
})
.catch(err => {
Menu.findAll()
.then(menus => {
Restaurant.findAll()
.then(restaurants => {
res.render('menu', { menus, restaurants, error: err.errors[0].message, format })
// res.send({ error: err.errors[0].message })
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
})
})
})

router.get('/:id/edit', (req, res) => {
let inputId = req.params.id
Menu.findById(inputId)
.then(menu => {
Restaurant.findAll()
.then(restaurants => {
// res.send({ menu, restaurants })
res.render('menu-edit-form',{ menu, restaurants })
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
})
})

router.post('/:id/edit', (req, res) => {
let inputId = req.params.id
let objMenu = req.body
Menu.update(objMenu, {
where: {
id: inputId
}
})
.then(() => {
res.redirect('/menus')
})
})

router.get('/:id/delete', (req, res) => {
let inputId = req.params.id
Menu.destroy({
where: {
id: inputId
}
})
.then(() => {
res.redirect('/menus')
})
})

module.exports = router;
47 changes: 47 additions & 0 deletions routers/restaurant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const express = require('express')
const router = express.Router()
const Model = require('../models')
const Menu = Model.Menu
const Restaurant = Model.Restaurant
const format = require('../helpers/helper')

router.get('/', (req, res) => {
Restaurant.findAll()
.then(restaurants => {
res.render('restaurant', { restaurants })
})
})

router.get('/:id/view_menu', (req, res) => {
let inputId = req.params.id
Restaurant.findById(inputId,{
include: [ Menu ]
})
.then(restaurant => {
let objKey = []
restaurant.Menus.forEach(menu => {
let parsedMenu = JSON.parse(JSON.stringify(menu))
objKey=(Object.keys(parsedMenu))
})
let key = objKey.slice(1,objKey.length-3)
// res.send({restaurant, key: key})
res.render('restaurant-menu',{ restaurant, key: key})
})
})

router.post('/:id/view_menu', (req, res) => {
let inputId = req.params.id
let obj = req.body
// console.log(obj);
Restaurant.findOne({
include: [ Menu ],
where: {
prop[0]:prop[1]
}
})
.then(joinedData => {
res.send(joinedData)
})
})

module.exports = router;
26 changes: 26 additions & 0 deletions seeders/20180301021716-seed-data-to-restaurant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Restaurants', [{
name : 'Bunga Rampai',
address : 'Menteng',
createdAt : new Date(),
updatedAt : new Date()
},{
name : 'GAIA Altitude',
address : 'Thamrin',
createdAt : new Date(),
updatedAt : new Date()
},{
name : 'Lucy in The Sky',
address : 'Kuningan',
createdAt : new Date(),
updatedAt : new Date()
}]);
},

down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('Restaurants', null, {});
}
};
Loading