Skip to content

Commit

Permalink
Storing data in Postgres change
Browse files Browse the repository at this point in the history
rafaelafpro committed Jul 28, 2020

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent a1449b2 commit 88a0a69
Showing 27 changed files with 703 additions and 269 deletions.
24 changes: 0 additions & 24 deletions data.json

This file was deleted.

134 changes: 134 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -5,14 +5,16 @@
"main": "server.js",
"scripts": {
"start": "npm-run-all -p nodemon browsersync",
"nodemon": "nodemon server.js",
"browsersync": "browser-sync start --proxy http://localhost:5000 --files 'public, views'"
"nodemon": "nodemon src/server.js",
"browsersync": "browser-sync start --proxy http://localhost:5000 --files 'public, src/app/views'"
},
"author": "Rafael Andrade",
"dependencies": {
"express": "^4.17.1",
"intl": "^1.2.5",
"nunjucks": "^3.2.1"
"method-override": "^3.0.0",
"nunjucks": "^3.2.1",
"pg": "^8.3.0"
},
"devDependencies": {
"browser-sync": "^2.26.7",
22 changes: 9 additions & 13 deletions public/script.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
modalOverlay = document.querySelector('.modal-overlay');
cards = document.querySelectorAll('.card');
courseCards = document.querySelector ('.course-card')


for (let card of cards) {
card.addEventListener ('click', ()=> {
let page = card.getAttribute('id');
window.location.href = `/courses/${page}`;
})
}


const currentPage = location.pathname
const menuItems = document.querySelectorAll("header .links a")

console.log(currentPage);
console.log(menuItems);


for (item of menuItems) {
if (currentPage.includes(item.getAttribute("href"))){
item.classList.add("active")
}
}
25 changes: 23 additions & 2 deletions public/style.css
Original file line number Diff line number Diff line change
@@ -235,11 +235,13 @@ button, .info a {
}

.table-teachers th {
margin-top: 16px;
text-align: left;
padding: 16px 0;
text-transform: uppercase;
color: var(--primary-color);
font-size: 14px;
padding: 16px 0;
border-bottom: 1px solid rgba(128, 128, 128, 0.384);
}


@@ -288,10 +290,29 @@ button, .info a {
background-color: var(--primary-color);
padding: 8px 16px;
border-radius: 8px;
position: relative;
/* position: relative; */
font-size: 14px;
transition: 200ms ease-in-out;
}

.table-teachers #new-button {
display: inline-block;
margin-bottom: 24px;
position: relative;
padding-left: 40px;
}

.table-teachers #new-button span {
position: absolute;
left: 0;
top: 0;
padding: 8px 12px;
font-size: 14px;
background-color: rgba(255, 255, 255, 0.233);
margin-right: 8px;
border-radius: 8px 0 0 8px;
}

.table-teachers a:hover {
background-color: #4c60b8;
transition: 200ms ease-in-out;
30 changes: 0 additions & 30 deletions routes.js

This file was deleted.

123 changes: 123 additions & 0 deletions src/app/controllers/students.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
const { simpleDate, age, graduation, grade } = require('../../lib/utils.js');
const Intl = require('intl');



module.exports = {
index(req, res) {
let students = new Object(data.students);

for (student of students){
student.level = grade(student.level)
}

return
},
create(req, res) {
return
},
post(req, res) {
const keys = Object.keys(req.body);

for (key of keys){
if (req.body[key] == '') {
return res.send ("Please, fill all forms");
}
}


const birth = Date.parse(req.body.birth)

let id = 1;

if (data.students.length >= 1) {
id = data.students.length + 1
}

data.students.push({
id,
...req.body,
birth
})

return
},
show(req, res) {
// const { id } = req.params;

// if (id > data.students.length){
// return res.send("Usuario inválido");
// }


// const foundStudent = data.students.find(function(student){
// return student.id == id;
// })


// const student = {
// ...foundStudent,
// age: age(foundStudent.birth)
// }

return

},
edit(req, res){
const { id } = req.params;

if (id > data.students.length){
return res.send("Usuario inválido");
}

const foundUser = data.students.find(function (student){
return id == student.id;
})

const student = {
...foundUser,
date: simpleDate(foundUser.birth)
}

return res.render('students/edit', { student })
},
put(req, res) {
let { id } = req.body;

id = Number(id);

let index = 0;

const foundStudent = data.students.find(function(student, foundIndex){
if (student.id == id) {
index = foundIndex;
return true;
}
})

const student = {
...foundStudent,
...req.body,
birth: Date.parse(req.body.birth),
id: Number(req.body.id)
}

data.students[index] = student;

return
},
delete(req, res) {
let { id } = req.body

id = Number(id);

const filteredStudents = data.students.filter(function(student){
return (student.id != id)
})

data.students = filteredStudents

return
},

}
60 changes: 60 additions & 0 deletions src/app/controllers/teachers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const { simpleDate, age, graduation, grade } = require('../../lib/utils.js');
const Intl = require('intl');
const Teacher = require('../models/Teacher.js')



module.exports = {
index(req, res) {
Teacher.all(function(results){
for (let i=0 ; i < results.length ; i++){
results[i].subjects_taught = results[i].subjects_taught.split(',')
}
return res.render('teachers/index', {teachers: results})
})
},

create(req, res) {
return res.render("teachers/create")
},

post(req, res) {
const keys = Object.keys(req.body);

for (key of keys){
if (req.body[key] == '') {
return res.send ("Please, fill all forms");
}
}


Teacher.create(req.body, function(teacher){
return res.redirect(`teachers/${teacher.id}`)
})
},
show(req, res){
const {id} = req.params

Teacher.find(id, function(teacher){
if (!teacher) return res.send("Teacher not found")

teacher.age = age(teacher.birth_date)
teacher.education_level = graduation(teacher.education_level)
teacher.subjects_taught = teacher.subjects_taught.split(',')
teacher.created_at = simpleDate(teacher.created_at).format

return res.render('teachers/show', {teacher})
})

},

edit(req, res){
return
},
put(req, res){
return
},
delete(req, res){
return
}
}
57 changes: 57 additions & 0 deletions src/app/models/Teacher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const { simpleDate, age, graduation, grade } = require('../../lib/utils.js');
const db = require('../../config/db.js')

module.exports = {

all(callback){
db.query('SELECT * FROM teachers', function(err, results){
if (err) throw `Database error! ${err}`

callback(results.rows)
})
},

create(data, callback){
const query = `
INSERT INTO teachers (
avatar_url,
name,
birth_date,
education_level,
class_type,
subjects_taught,
created_at
) VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id
`

const values = [
data.avatar_url,
data.name,
simpleDate(data.birth_date).iso,
data.education_level,
data.class_type,
data.subjects_taught,
simpleDate(Date.now()).iso
]


db.query(query, values, function(err, results){
if (err) throw `Database Error ${err}`

callback(results.rows[0])
})
},

find(id, callback) {

db.query(`
SELECT *
FROM teachers
WHERE id = $1`, [id], function(err, results){
console.log('Executando db query...');
if (err) throw `Database Error! ${err}`
callback(results.rows[0])
})
},
}
4 changes: 2 additions & 2 deletions views/layout.njk → src/app/views/layout.njk
Original file line number Diff line number Diff line change
@@ -19,7 +19,7 @@
<img src="/assets/logo.png" alt="Digius logo">
</div>
<div class="links">
<a href="/" class="active">Teachers</a>
<a href="/teachers">Teachers</a>
<a href="/students">Students</a>
</div>
</div>
@@ -35,6 +35,6 @@




<script src="script.js"></script>
</body>
</html>
13 changes: 13 additions & 0 deletions src/app/views/students/confirm-delete.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
const deleteButton = document.querySelector("#delete-form button")
deleteButton.addEventListener("click", (event)=> {
const confirmation = confirm("Deseja realmente deletar?")
if (!confirmation){
event.preventDefault()
}
})
</script>
16 changes: 16 additions & 0 deletions src/app/views/students/create.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{% extends "layout.njk" %}

{% block content %}

<form class="card" method="POST" action="/students">
<section class="avatar" style="background: url('https://source.unsplash.com/collection/8874679/600x800') no-repeat center center / cover"></section>
<section class="info">
<h3>CADASTRO DE ESTUDANTE</h3>

{% include 'students/fields.njk' %}

</section>

</div>

{% endblock content %}
30 changes: 30 additions & 0 deletions src/app/views/students/edit.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{% extends "layout.njk" %}

{% block content %}

<div class="card">
<section class="avatar" style="background: url({{student.avatar_url}}) no-repeat center center / cover"></section>
<section class="info">
<form method="POST" action="/students?_method=PUT">
<h3>EDITAR PROFESSOR</h3>

{% include 'students/fields.njk' %}

<input type="hidden" name="id" value="{{ student.id }}">
</form>

<form id="delete-form" method="POST" action="/students?_method=DELETE" >
<input type="hidden" name="id" value="{{ student.id }}">
<button type="submit">Deletar</button>
</form>

</section>

</div>

{% include 'students/confirm-delete.njk' %}




{% endblock content %}
38 changes: 38 additions & 0 deletions src/app/views/students/fields.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

<div class="item">
<div>URL do Avatar</div>
<input type="url" name="avatar_url" placeholder="https://" value="{{student.avatar_url}}">
</div>
<div class="item">
<div>Nome</div>
<input type="text" name="name" placeholder="Digite o seu nome completo" value="{{student.name}}">
</div>
<div class="item">
<div>Data de Nascimento</div>
<input type="date" name="birth" value="{{student.date}}">
</div>
<div class="item">
<div>E-mail</div>
<input type="email" name="email" value="{{student.email}}">
</div>
<div class="item">
<div>Ano escolar</div>
<select name="level">
<option value="" selected disabled>Selecione o seu ano escolar</option>
<option value="5f" {% if student.level == '5f' %} selected {% endif %}>5º ano do Ensino Fundamental</option>
<option value="6f" {% if student.level == '6f' %} selected {% endif %}>6º ano do Ensino Fundamental</option>
<option value="7f" {% if student.level == '7f' %} selected {% endif %}>7º ano do Ensino Fundamental</option>
<option value="8f" {% if student.level == '8f' %} selected {% endif %}>8º ano do Ensino Fundamental</option>
<option value="9f" {% if student.level == '9f' %} selected {% endif %}>9º ano do Ensino Fundamental</option>
<option value="1a" {% if student.level == '1a' %} selected {% endif %}>1º ano do Ensino Médio</option>
<option value="2a" {% if student.level == '2a' %} selected {% endif %}>2º ano do Ensino Médio</option>
<option value="3a" {% if student.level == '3a' %} selected {% endif %}>3º ano do Ensino Médio</option>
</select>
</div>

<div class="item">
<div>Carga Horária Semanal</div>
<input type="number" name="charge" placeholder="Quantidade de horas por semana" value='{{ student.charge }}'>
</div>

<button type="submit">Enviar</button>
45 changes: 45 additions & 0 deletions src/app/views/students/index.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{% extends "layout.njk" %}

{% block content %}
<div class="card table-teachers">

<a id="new-button" href="/students/create"><span>+</span>NOVO</a>

<table>

<thead>
<tr>
<th>Estudante</th>
<th>Email</th>
<th>Ano Escolar</th>
<th>Ação</th>
<tr>

</thead>



<tbody>

{% for student in students %}
<tr>
<td>
<span style="background-image: url('{{student.avatar_url}}')"></span>
{{ student.name }}
</td>
<td>
{{ student.email }}
</td>
<td>
{{ student.level }}
</td>
<td><a href="/students/{{student.id}}">VER</a>
</tr>
{% endfor %}

</tbody>

</table>
</div>

{% endblock content %}
47 changes: 47 additions & 0 deletions src/app/views/students/show.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{% extends "layout.njk" %}

{% block content %}

<div class="card">
<section class="avatar" style="background: url('{{ student.avatar_url }}') no-repeat center center / cover"></section>
<section class="info">
<h3>ESTUDANTE</h3>
<div class="item">
<div>Nome</div>
<div>{{ student.name }}</div>
</div>
<div class="item">
<div>Idade</div>
<div>{{ student.age }}</div>
</div>
<div class="item">
<div>E-mail</div>
<div>{{ student.email }}</div>
</div>
<div class="item">
<div>Ano Escolar</div>
<div>
{% if student.level == '5f' %}5º ano do Ensino Fundamental{% endif %}
{% if student.level == '6f' %}6º ano do Ensino Fundamental{% endif %}
{% if student.level == '7f' %}7º ano do Ensino Fundamental{% endif %}
{% if student.level == '8f' %}8º ano do Ensino Fundamental{% endif %}
{% if student.level == '9f' %}9º ano do Ensino Fundamental{% endif %}
{% if student.level == '1a' %}1º ano do Ensino Médio{% endif %}
{% if student.level == '2a' %}2º ano do Ensino Médio{% endif %}
{% if student.level == '3a' %}3º ano do Ensino Médio{% endif %}
</div>
</div>
<div class="item">
<div>Carga horária</div>
<div>{{ student.charge }}</div>
</div>



<a href='/students/{{ student.id }}/edit'>Editar</a>

</section>

</div>

{% endblock content %}
File renamed without changes.
File renamed without changes.
34 changes: 34 additions & 0 deletions src/app/views/teachers/fields.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

<div class="item">
<div>URL do Avatar</div>
<input type="url" name="avatar_url" placeholder="https://" value="{{teacher.avatar_url}}">
</div>
<div class="item">
<div>Nome</div>
<input type="text" name="name" placeholder="Digite o seu nome completo" value="{{teacher.name}}">
</div>
<div class="item">
<div>Data de Nascimento</div>
<input type="date" name="birth_date" value="{{teacher.date}}">
</div>
<div class="item">
<div>Grau de Escolaridade</div>
<select name="education_level">
<option value="" selected disabled>Selecione o seu grau de escolaridade</option>
<option value="medio" {% if teacher.education_level == 'medio' %} selected {% endif %}>Ensino Médio Completo</option>
<option value="superior" {% if teacher.education_level == 'superior' %} selected {% endif %}>Ensino Superior Completo</option>
<option value="mestrado" {% if teacher.education_level == 'mestrado' %} selected {% endif %}>Mestrado</option>
<option value="doutorado" {% if teacher.education_level == 'doutorado' %} selected {% endif %}>Doutorado</option>
</select>
</div>
<div class="item">
<div>Tipo de Aula</div>
<span><input type="radio" name="class_type" value="Presencial" {% if teacher.class_type == 'Presencial' %} checked {% endif %}>Presencial</span>
<span><input type="radio" name="class_type" value="À distância" {% if teacher.class_type == 'À distância' %} checked {% endif %}>À distância</span>
</div>
<div class="item">
<div>Área de Atuação</div>
<input type="text" name="subjects_taught" placeholder="Quais matérias você leciona? Separe por vírgulas" value='{{ teacher.subjects_taught }}'>
</div>

<button type="submit">Enviar</button>
Original file line number Diff line number Diff line change
@@ -2,6 +2,9 @@

{% block content %}
<div class="card table-teachers">

<a id="new-button" href="/teachers/create"><span>+</span>NOVO</a>

<table>

<thead>
@@ -23,7 +26,7 @@
{{teacher.name}}
</td>
<td>
{% for discipline in teacher.disciplines %}
{% for discipline in teacher.subjects_taught %}
<span>{{ discipline }}</span>
{% endfor %}
</td>
6 changes: 3 additions & 3 deletions views/teachers/show.njk → src/app/views/teachers/show.njk
Original file line number Diff line number Diff line change
@@ -16,16 +16,16 @@
</div>
<div class="item">
<div>Grau de Escolaridade</div>
<div>{{ teacher.level }}</div>
<div>{{ teacher.education_level }}</div>
</div>
<div class="item">
<div>Tipo de Aula</div>
<div>{{ teacher.type }}</div>
<div>{{ teacher.class_type }}</div>
</div>
<div class="item">
<div>Acompanhamento</div>
<div>
{%for discipline in teacher.disciplines %}
{%for discipline in teacher.subjects_taught %}
<span>{{ discipline }}</span>
{% endfor %}
</div>
9 changes: 9 additions & 0 deletions src/config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { Pool } = require('pg')

module.exports = new Pool({
user: 'postgres',
password: 'postgres',
host: 'localhost',
port: '5432',
database: 'my_teacher'
})
29 changes: 23 additions & 6 deletions utils.js → src/lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
age: function(timestamp) {
age(timestamp) {
const today = new Date();
const birthDate = new Date(timestamp);

@@ -13,22 +13,39 @@ module.exports = {
return age;
},

simpleDate: function(timestamp) {
simpleDate(timestamp) {
const date = new Date(timestamp);
const year = date.getUTCFullYear();
const month = `0${date.getUTCMonth()+1}`.slice(-2);
const day = `0${date.getUTCDate()}`.slice(-2);

const dateString = `${year}-${month}-${day}`;

return dateString;
return {
day,
month,
year,
iso: `${year}-${month}-${day}`,
birthDay: `${day}/${month}`,
format: `${day}/${month}/${year}`
}
},

graduation: function(level){

graduation(level){
if (level == 'mestrado') return 'Mestrado'
if (level == 'doutorado') return 'Doutorado'
if (level == 'medio') return 'Ensino Médio Completo'
if (level == 'superior') return 'Ensino Superior Completo'
},

grade(level){
if (level == '5f') return "5º ano do Ensino Fundamental"
if (level == '6f') return "6º ano do Ensino Fundamental"
if (level == '7f') return "7º ano do Ensino Fundamental"
if (level == '8f') return "8º ano do Ensino Fundamental"
if (level == '9f') return "9º ano do Ensino Fundamental"
if (level == '1a') return "1º ano do Ensino Médio"
if (level == '2a') return "2º ano do Ensino Médio"
if (level == '3a') return "3º ano do Ensino Médio"
}

}
27 changes: 27 additions & 0 deletions src/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const express = require('express');
const routes = express.Router();
const teachers = require('./app/controllers/teachers')
const students = require('./app/controllers/students')

routes.get('/', function(req,res){
return res.redirect("/teachers");
})

routes.get('/teachers', teachers.index)
routes.post('/teachers', teachers.post)
routes.get('/teachers/create', teachers.create)
routes.get('/teachers/:id', teachers.show)
routes.get('/teachers/:id/edit', teachers.edit)
routes.put('/teachers', teachers.put);
routes.delete('/teachers', teachers.delete);

routes.get('/students', students.index)
routes.post('/students', students.post)
routes.get('/students/create', students.create)
routes.get('/students/:id', students.show)
routes.get('/students/:id/edit', students.edit)
routes.put('/students', students.put);
routes.delete('/students', students.delete);


module.exports = routes;
2 changes: 1 addition & 1 deletion server.js → src/server.js
Original file line number Diff line number Diff line change
@@ -19,7 +19,7 @@ server.use(routes);
server.set("view engine", "njk");

// configuração nunjucks
nunjucks.configure("views", {
nunjucks.configure("src/app/views", {
express: server,
noCache: true,
autoescape: false
150 changes: 0 additions & 150 deletions teachers.js

This file was deleted.

34 changes: 0 additions & 34 deletions views/teachers/fields.njk

This file was deleted.

0 comments on commit 88a0a69

Please sign in to comment.