Skip to content
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 .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_URL=postgres://cqhtnddixgllci:dc4fcf23b5a7376f3ac52e457517d1394214a15fe4f0394d2cc1d81cb1b1547d@ec2-107-20-167-11.compute-1.amazonaws.com:5432/d5nmioocfiob3n
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# dependencies
node_modules

# misc
.DS_Store
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: node index.js
Binary file added data/db.sqlite3
Binary file not shown.
12 changes: 12 additions & 0 deletions data/migrations/20190220165940_migration_NoteTable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

exports.up = function(knex, Promise) {
return knex.schema.createTable('NoteTable', (table) =>{
table.increments('_id');
table.string('title').notNullable();
table.string('textBody').notNullable();
})
};

exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('NoteTable')
};
16 changes: 16 additions & 0 deletions data/seeds/seed_NoteTable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('NoteTable').truncate()
.then(function () {
// Inserts seed entries
return knex('NoteTable').insert([
{title: 'Note Title1',textBody: 'Note Body1'},
{title: 'Note Title2',textBody: 'Note Body2'},
{title: 'Note Title3',textBody: 'Note Body3'},
{title: 'Note Title4',textBody: 'Note Body4'},
{title: 'Note Title5',textBody: 'Note Body5'}

]);
});
};
14 changes: 14 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const express = require('express');
const Middleware = require('./middleware/middleware.js')
const server = express();
const PORT = process.env.PORT || 3111;


// ** IMPORTING MIDDLEWARE ** //

Middleware(server);


server.listen( PORT, ()=>{
console.log(`\n //*** -LAMBDA NOTES SERVER - Listening on http://localhost:${PORT} ***//\n`)
})
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();

// for local postgress db config
const localPg = {
host:'localhost',
database :'db',
user :process.env.DB_USER,
password :process.env.DB_PASS,
};

const dbConnection = process.env.DATABASE_URL || localPg

module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: './data/db.sqlite3'
},
useNullAsDefault :true,
migrations: {
directory: './data/migrations'
},
seeds: {
directory: './data/seeds'
}
},
production: {
client: 'pg',
connection: dbConnection,
pool:{
min:2,
max:10,
},

migrations: {
directory: './data/migrations'
},
seeds: {
directory: './data/seeds'
}
}
}
50 changes: 50 additions & 0 deletions middleware/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const express = require('express');
const helmet = require('helmet');
const morgan = require('morgan');
const cors = require('cors');
const RouterForNoteApp = require('../routers/routers');
const options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}


module.exports = (server) =>{
server.use(
express.json(),
cors(),
helmet(),
morgan('dev'),

);

server.use('/note', RouterForNoteApp);
server.use(function(req, res, next){
res.status(404);

// respond with html page
if (req.accepts('html')) {
res.render('404', { url: req.url });
return;
}

// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}

// default to plain-text. send()
res.type('txt').send('Not found');
});
server.set('etag', false) ;


}
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "projectbackend",
"version": "1.0.0",
"description": "'build a backend for a note taking app called \"Lambda Notes'",
"main": "index.js",
"scripts": {
"server": "nodemon"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Witanday/back-end-project-week.git"
},
"keywords": [
"nodes",
"express"
],
"author": "Witanday Kyanga /LAMBDA WEBPT2",
"license": "ISC",
"bugs": {
"url": "https://github.com/Witanday/back-end-project-week/issues"
},
"homepage": "https://github.com/Witanday/back-end-project-week#readme",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^6.2.0",
"express": "^4.16.4",
"helmet": "^3.15.1",
"knex": "^0.16.3",
"morgan": "^1.9.1",
"nodemon": "^1.18.10",
"pg": "^7.8.1",
"sqlite3": "^4.0.6"
}
}
23 changes: 23 additions & 0 deletions routers/routers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const express = require('express');
const RouterNote = express.Router();
const TaskManager = require('../taskmanager/taskmanager');


// ** ROUTERS FOR OUR LAMBDA NOTES APP ** //

// ## GET ALL NOTES
RouterNote.get('/get/all',TaskManager.getAllNotes);

// ## GET A NOTE
RouterNote.get('/get/:_id',TaskManager.getNotebyId);

// ## CREATE A NOTE/create
RouterNote.post('/create',TaskManager.CreateNewNote);

// ## EDIT A NOTE
RouterNote.put('/edit/:_id',TaskManager.UpdateNote);

// ## DELETE A NOTE
RouterNote.delete('/delete/:_id',TaskManager.DestroyNote);

module.exports = RouterNote;
147 changes: 147 additions & 0 deletions taskmanager/taskmanager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// **CONNECTION TO OUR DB (production)***
const knex = require('knex');
const dbEngine = process.env.DB || 'development';
// add DB to point to production on heroku
const config = require('../knexfile.js')[dbEngine];
//const db= require('knex')(config);
const tbl = 'NoteTable';
const db= knex(config);

/*// **CONNECTION TO OUR DB development***
const knex = require('knex');
const knexConfing = require('../knexfile.js');
const db = knex(knexConfing.development);
const tbl = 'NoteTable';
*/

// GET ALL NOTES HANDLER

const getAllNotes =(req,res)=>{
db(tbl).then(notes =>{
if(notes){
res.status(200).json(notes)
}
else{
res.status(405).json({errorMessage : 'No note yet stored in the Database'})
}})
.catch(err =>{res.status(500).json(err)})
}

// GET A NOTE HANDLER

const getNotebyId =(req,res)=>{
const {_id} = req.params
db(tbl)
.where({_id})
.then(note => {
if(note.length !== 0){
res.status(200).json(note)
}
else{
res.status(404).json({errorMessage :'HOOOPS NOT FOUND !!!'})
}

}).catch(err =>{res.status(500).json(err)})
}


// CREATE A NOTE HANDLER

const CreateNewNote = (req,res)=> {
const newNote = req.body;
if(newNote.title && newNote.textBody){
db(tbl)
.insert(newNote)
.then(_id => {
res.status(200).json(`Success, new note created with id :${_id}`)
})
.catch(err =>{res.status(500).json(err)})
}

else{
res.status(450).json({errorMessage :'Hoops, all fields are required'})
}
}



// EDIT OR UPDATE A NOTE HANDLER

const UpdateNote = (req,res)=>{
const eDITNote = req.body;
const {_id} = req.params
if(eDITNote.title && eDITNote.textBody){
db(tbl)
.where({_id})
.then(note => {
if(note.length !== 0){
db(tbl)
.where({_id})
.update(eDITNote)
.then(note => {
res.status(200).json(`Success,${note} note updated with id :${_id}`)
})
.catch(err =>{res.status(500).json(err)})
}
else{
res.status(404).json({errorMessage :'HOOOPS NOT FOUND !!!'})
}})}

else{
res.status(450).json({errorMessage :'Hoops, all fields are required'})
}
}


// GET A NOTE HANDLER

const DestroyNote =(req,res)=>{
const {_id} = req.params
db(tbl)
.where({_id})
.then(note => {
console.log(note)
if(note.length !== 0){
db(tbl)
.where({_id}).del()
.then(count =>{
res.status(200).json(`Success,${count} note deleted with id :${_id}`)
})


}
else{
res.status(404).json({errorMessage :'HOOOPS NOT FOUND !!!'})
}

}) .catch(err =>{res.status(500).json(err)})
}
/*
// ****Easiest route pre-test****
const notes = [
{
"tags": ["tag", "otherTag"],
"title": "Note Title",
"textBody": "Note Body",
}]
const testRoute = (routename) =>{
return(req, res) =>{
// just for sipmle test
res.json({notes,routename:[routename]})
}
}
const getNotebyId = testRoute('getNotebyId') ;
const getAllNotes = testRoute('getAllNotes') ;
const CreateNewNote = testRoute('CreateNewNote') ;
const DestroyNote = testRoute('DestroyNote') ;
const UpdateNote= testRoute(' UpdateNote') ;
*/

module.exports = {
getNotebyId,
getAllNotes,
CreateNewNote,
DestroyNote,
UpdateNote

}
Loading