Skip to content

Commit

Permalink
almost finsih client/api
Browse files Browse the repository at this point in the history
  • Loading branch information
mate2 authored and Jerome committed Jun 3, 2018
1 parent c8ef913 commit 14a1ae8
Show file tree
Hide file tree
Showing 16 changed files with 484 additions and 209 deletions.
149 changes: 149 additions & 0 deletions apiServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
var createError = require('http-errors');
var express = require('express');
var cookieParser = require('cookie-parser');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// APIs
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/universalmern');

var db = mongoose.connection;
db.on('error', console.error.bind(console, '# MongoDB - connection error : '));

// -->> SET UP SESSIONS <<--
app.use(session({
secret: 'mySecretString',
saveUninitialized: false,
resave: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 2 // in milliseconds
},
store: new MongoStore({
mongooseConnection: db,
ttl: 2 * 24 * 60 * 60
// ttl: 2 * 86400
})
}));

// SAVE TO SESSION CART API
app.post('/cart', (req, res) => {
const cart = req.body;
req.session.cart = cart;
req.session.save((err) => {
if(err) {
throw err;
}
res.json(req.session.cart);
});
});
// GET SESSION CART API
app.get('/cart', (req, res) => {
if(typeof req.session.cart !== 'undefined') {
res.json(req.session.cart);
}
});
// -->> END SET UP SESSIONS <<--


const Books = require('./models/books');

// -->> GET BOOKS <<--
app.get('/books', (req, res) => {
Books.find((err, books) => {
if(err) {
throw err;
}
res.json(books);
});
});

// -->> POST BOOKS <<--
app.post('/books', (req, res) => {
const book = req.body;

Books.create(book, (err, books) => {
if(err) {
throw err;
}
res.json(books);
});
});

// -->> PUT BOOKS <<--
app.put('/books/:_id', (req, res) => {
const book = req.body;
const query = {_id: req.params._id};

// IF teh field does not exist $set will set a new field
const update = {
title: book.title,
description: book.description,
image: book.image,
price: book.price
};

// When set to true, returns the updated document
const options = {new: true};

Books.findOneAndUpdate(query, update, options, (err, books) => {
if(err) {
throw err;
}
res.json(books);
});
});

// -->> DELETE BOOKS <<--
app.delete('/books/:_id', (req, res) => {
const query = {_id: req.params._id};

Books.remove(query, (err, books) => {
if(err) {
throw err;
}
res.json(books);
});
});

// -->> DELETE BOOKS <<--
app.get('/images', (req, res) => {
const imgFolder = __dirname + '/public/images/';
// REQUIRE FILE SYSTEM
const fs = require('fs');
// READ ALL FILES IN DIRECTORY
fs.readdir( imgFolder, (err, files) => {
if(err) {
return console.error(err);
}
// Create an empty array
const filesArr = [];
// ITERATE ALL IMAGES IN THE DIRECTORY AND ADD TO THE ARRAY
files.forEach((file) => {
if(file !== '.gitignore') {
filesArr.push({name: file});
}
});
// SEND THE JSON RESPONSE WITH THE ARRAY
res.json(filesArr);
});
});

// END APIs

app.listen(3001, function(err){
if(err){
return console.log(err);
}
console.log('API server is listening on http://localhost:3001');
});
85 changes: 11 additions & 74 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,90 +1,27 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// PROXY
var httpProxy = require('http-proxy');

var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// APIs
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/universalmern');

const Books = require('./models/books');

// -->> GET BOOKS <<--
app.get('/books', (req, res) => {
Books.find((err, books) => {
if(err) {
throw err;
}
res.json(books);
});
});

// -->> POST BOOKS <<--
app.post('/books', (req, res) => {
const book = req.body;

Books.create(book, (err, books) => {
if(err) {
throw err;
}
res.json(books);
});
// Proxy to api
const apiProxy = httpProxy.createProxyServer({
target: 'http://localhost:3001'
});

// -->> PUT BOOKS <<--
app.put('/books/:_id', (req, res) => {
console.log('im here');
const book = req.body;
const query = {_id: req.params._id};

// IF teh field does not exist $set will set a new field
const update = {
title: book.title,
description: book.description,
image: book.image,
price: book.price
};

// When set to true, returns the updated document
const options = {new: true};

Books.findOneAndUpdate(query, update, options, (err, books) => {
if(err) {
throw err;
}
res.json(books);
});
app.use('/api', function(req, res){
apiProxy.web(req, res);
});
// End proxy to pai

// -->> DELETE BOOKS <<--
app.delete('/books/:_id', (req, res) => {
const query = {_id: req.params._id};

Books.remove(query, (err, books) => {
if(err) {
throw err;
}
res.json(books);
});
});

// END APIs
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
Expand All @@ -106,4 +43,4 @@ app.use(function(err, req, res, next) {
res.render('error');
});

module.exports = app;
module.exports = app;
3 changes: 3 additions & 0 deletions books.db.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@
{
"title" : "The Maze Runner",
"description" : "First of the trilogy",
"images" : "/images/mr1.jpg",
"price" : 9.99
},
{
"title" : "The Maze Runner: Scorch Trials",
"description" : "Second of the trilogy",
"images" : "/images/mr2.jpg",
"price" : 10.99
},
{
"title" : "The Maze Runner: The Death Cure",
"description" : "third of the trilogy",
"images" : "/images/mr3.jpg",
"price" : 11.99
}
]
35 changes: 18 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
{
"name": "universal-mern-training",
"version": "1.0.0",
"description": "",
"main": "index.js",
"version": "0.0.0",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "node ./bin/www & node apiServer.js",
"nodemon": "nodemon ./bin/www & nodemon apiServer.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mate2/universal-mern-training.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/mate2/universal-mern-training/issues"
},
"homepage": "https://github.com/mate2/universal-mern-training#readme",
"dependencies": {
"axios": "^0.18.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"connect-mongo": "^2.0.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "^4.16.2",
"express-session": "^1.15.6",
"http-errors": "~1.6.2",
"http-proxy": "^1.17.0",
"jade": "~1.11.0",
"mongoose": "^5.1.2",
"morgan": "~1.9.0",
"nodemon": "^1.17.5",
"react": "^16.3.2",
"react-bootstrap": "^0.32.1",
"react-dom": "^16.3.2",
"react-redux": "^5.0.7",
"react-router": "3.0.2",
"redux": "^3.7.2"
"react-router": "3.2.0",
"redux": "^3.7.2",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"redux-logger": "^3.0.6",
Expand Down
1 change: 1 addition & 0 deletions public/images/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.jpg
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const path = require('path');
// Middleware to define folder for static files (images)
app.use(express.static('public'))

app.get('/', (req, res) => {
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

Expand Down
Loading

0 comments on commit 14a1ae8

Please sign in to comment.