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

Joe Mercado - Backend project Week #496

Open
wants to merge 3 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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
.DS_Store
node_modules
Old-Version-2
Old-Version
Old-Version-3
Old-Version-4
3 changes: 3 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"esversion": 6
}
4 changes: 4 additions & 0 deletions db/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const knex = require('knex');
const knexConfig = require('../knexfile.js');

module.exports = knex(knexConfig.development);
41 changes: 41 additions & 0 deletions db/helpers/Helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const db = require('../dbConfig');

module.exports = {

// ### Getting all the notes
getNotes: () => {
const query = db('notes');
return query.then(notes => {
return notes.map(note => {
return {
...note
}
})
})
},

// ### retrieve a note by its id
getNote: (id) => {
return db('notes').select().where('id', id);
},

// ### Posting a new note
addNote: (note) => {
return db('notes')
.insert(note)
},

// ### Updating note
updateNote: (id, updatedNote) => {
return db('notes')
.where('id', id)
.update(updatedNote)
},

// Deleting note
deleteNote: (id) => {
return db('notes')
.where('id', id)
.delete()
},
}
14 changes: 14 additions & 0 deletions db/migrations/20190213_note.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
exports.up = function(knex, Promise) {
return knex.schema.createTable('notes', table => {
table.increments()
table.string('title', 128)
.notNullable()
table.text('content')
.notNullable()
})
};

exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('notes');
};

14 changes: 14 additions & 0 deletions db/migrations/20190213_users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
exports.up = function(knex, Promise) {
return knex.schema.createTable("users", table => {
table.increments()
table.string('username', 128)
.notNullable()
.unique()
table.string('password')
.notNullable()
});
};

exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('users');
};
Binary file added db/notes.sqlite3
Binary file not shown.
178 changes: 178 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const db = require('./db/helpers/Helper');
const dbUsers = require('./db/dbConfig');

const server = express();

server.use(helmet());
server.use(express.json());
server.use(cors());

const secret = 'secret';

const port = process.env.PORT || 9000;
require('dotenv').config();

// ########## Generating token ###########
function generateToken(user){
const payload = {
username: user.username
};

const options = {
expiresIn: '1h',
jwtid: '12345'
}
return jwt.sign(payload, secret, options);
}

// ####### Protected middleware ##########
function protected(req, res, next) {
const token = req.headers.authorization;
if (token) {
jwt.verify(token, secret, (error, decodedToken) => {
if (error) {
return res
.status(400)
.json({ Message: ' Invalid token' })
} else {
req.user = { username: decodedToken.username }
next()
}
})
} else {
return res.status(400).json({ Message: 'No token found' })
}
}


server.get('/', (req, res) => {
res.send('API running....')
});

// ########## GET ALL NOTES ################
server.get('/notes', (req, res) => {
db.getNotes()
.then(notes => res.status(200).json(notes))
.catch(err => res.status(500).json(err))
});

// ########### GET NOTE BY ID ################
server.get('/notes/:id', (req, res) => {
const { id } = req.params;
db.getNote(id)
.then(notes => notes.find(note => note.id === +id))
.then(notes => {
if(notes) {
res.status(200).json(notes);
} else {
res.status(404).json({Message: 'The note with specified id does not exist!'});
}
})
.catch(error => {
res.status(500).json(error);
})
});

// ########## POSTING NEW NOTE ###########
server.post('/notes', (req, res) => {
const { title, content } = req.body;
const note = {
title,
content
};
if (!title || !content) {
res.status(400).json('Message: title and content are required fields!')
}

db.addNote(note)
.then(notes => {
res.status(200).json(notes);
})
.catch(error => {
res.status(500).json(error)
})
});

// ########### UPDATING NOTE ###########
server.put('/notes/:id', (req, res) => {
const {title, content} = req.body;
const {id} = req.params;
const updatedNote = {
title,
content
};
if (!title || !content) {
res.status(400).json('Message: In order to update note, title and content are required fields!')
}
db.updateNote(id, updatedNote)
.then(notes => {
res.status(200).json(notes)
})
.catch(error => {
res.status(500).json(error)
})
});

// ########### DELETE NOTE ###############
server.delete('/notes/:id', (req, res) => {
const {id} = req.params;
db.deleteNote(id)
.then(notes => {
res.status(200).json(notes)
})
.catch(error => {
res.status(500).json(error)
})
});


// ###### Registering newUser ############
server.post('/register', (req, res) => {
const newUser = req.body;
const hash = bcrypt.hashSync(newUser.password, 14);
newUser.password = hash;

dbUsers('users')
.insert(newUser)
.then(ids => {
db('users')
.where({ id: ids[0] })
.first()
.then(newUser => {
const token = generateToken(newUser);
res.status(201).json(token);
});
})
.catch(function(error) {
res.status(500).json({ error });
});
})

// ########### Login ##############
server.post('/login', (req, res) => {
const creds = req.body;

dbUsers('users')
.where({username: creds.username})
.first()
.then(user => {
if (user && bcrypt.compareSync(creds.password, user.password)) {
const token = generateToken(user);
res.status(200).json(token)
}
else {
return res.status(400).json({Message: 'Wrong credentials'})
}
})
.catch(error => {
res.status(500).json(error)
})
})

server.listen(port, () => console.log(`Running on ${port}.....`));
42 changes: 42 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

require('dotenv').config();
const localPg = {
host: 'localhost',
database: 'notes',
user: process.env.DB_USER,
password: process.env.DB_PASS,
};
const dbConnection = process.env.DATABASE_URL || localPg;

module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: './db/notes.sqlite3',
},
migrations: {
tableName: 'knex_migrations',
directory: './db/migrations',
},
seeds: {
directory: './db/seeds',
},
useNullAsDefault: true,
},

production: {
client: 'pg',
connection: dbConnection,
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: 'knex_migrations',
directory: './db/migrations',
},
seeds: {
directory: './db/seeds',
},
},
};
23 changes: 23 additions & 0 deletions lambda-notes/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
Loading