Skip to content

Commit

Permalink
Merge pull request #2 from oskarolaszczyk/api
Browse files Browse the repository at this point in the history
Api
  • Loading branch information
oskarolaszczyk authored Jan 10, 2021
2 parents dd728e7 + 8aa6db4 commit 45819aa
Show file tree
Hide file tree
Showing 19 changed files with 738 additions and 53 deletions.
28 changes: 23 additions & 5 deletions backend/app.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,44 @@
//zaladowanie modolow dodatkowych i plikow aplikacji
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
//var usersRouter = require('./routes/users');
var cors = require('cors');

const errors = require('./middlewares/errors')



//db
require('./db/mongoose')


var app = express();
app.options('*', cors())
app.use(cors());

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

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


app.use('/', indexRouter);
app.use('/users', usersRouter);
// errors handling
// app.use(errors.notFound());
// app.use(errors.catchErrors());
//app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
Expand All @@ -40,4 +56,6 @@ app.use(function(err, req, res, next) {
res.render('error');
});



module.exports = app;
11 changes: 11 additions & 0 deletions backend/controllers/CategoriesController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const Category = require('../db/models/category')



async function findAll(req, res) {
const categories = await Category.find().sort({ createdAt: 'desc' });
return res.status(200).send({ data: categories });
}


module.exports.findAll = findAll
3 changes: 3 additions & 0 deletions backend/controllers/IndexController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exports.home = (req, res) => {
res.json({'status':'working very well!'});
}
11 changes: 11 additions & 0 deletions backend/controllers/OrderStatusesController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const OrderStatus = require('../db/models/order-status')



async function findAll(req, res) {
const orderStatutes = await OrderStatus.find().sort({ createdAt: 'desc' });
return res.status(200).send({ data: orderStatutes });
}


module.exports.findAll = findAll
119 changes: 119 additions & 0 deletions backend/controllers/OrdersController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
const Order = require('../db/models/order');
const OrderStatus = require('../db/models/order-status')



async function findOne(req, res, next) {
const orderStatus = await OrderStatus.findOne({slug : req.params.slug})
if (!orderStatus) return res.status(404).send({message: `Order was not found` });

const ref = orderStatus._id

const orders = await Order.find({ orderStatus: ref }).populate({
path: 'products orderStatus',
populate: { path: 'product_id'}
});

if (!orders) return res.status(404).send({message: `Order was not found` });


return res.status(200).send({ data: orders });
}

async function findAll(req, res) {
const orders = await Order.find().sort({ createdAt: 'desc' })
.populate({
path: 'products orderStatus',
populate: { path: 'product_id'}
});
return res.status(200).send({ data: orders });
}

async function create(req, res) {
try {
console.log(req.body.products)
const order = await new Order({
date: req.body.date,
orderStatus: req.body.orderStatusID,
userName: req.body.userName,
email: req.body.email,
phone: req.body.phone,
products: req.body.products,

}).save()

return res.status(201).send({ data: order, message: `Order was created` });
} catch (err) {
return res.status(400).send({message: `Order was not created`, error: err });

}
}

async function update(req, res, next) {
try {

const orderStatus = await OrderStatus.findOne({slug : req.body.orderStatusID})
if (!orderStatus) return res.status(400).send({message: `Order was not updated21`});

const reference = orderStatus._id

let order = await Order.findOne({ _id: req.params.id});
if (!order) return res.status(404).send({message: `Order was not updated` });


const canceled = await OrderStatus.findOne({slug : "canceled"})
const notApproved = await OrderStatus.findOne({slug : "not-approved"})
const approved = await OrderStatus.findOne({slug : "approved"})
const completed = await OrderStatus.findOne({slug : "completed"})


if (order.orderStatus._id.equals(canceled._id))
return res.status(400).send({message: `Order was not updated`});

if (order.orderStatus._id.equals(approved._id) && (reference.equals(notApproved._id) || reference.equals(canceled._id)))
return res.status(400).send({message: `Order was not updated`});

if (order.orderStatus._id.equals(completed._id) && (reference.equals(notApproved._id) || reference.equals(approved._id) || reference.equals(canceled._id)))
return res.status(400).send({message: `Order was not updateded`});

const updatedOrder = await Order.updateOne(
{
_id: req.params.id
},
{$set:
{
//TODO walidacja dla nieustawiania zlego statusu
orderStatus: reference,


}})


} catch (err) {
return res.status(400).send({message: `Order was not updated`, error: err });
}




order = await Order.findOne({ _id: req.params.id }).populate({
path: 'products orderStatus',
populate: { path: 'product_id'}
});;
return res.status(200).send({ data: order, message: `Order was updated` });
}

async function remove(req, res, next) {
const order = await Order.findOne({ _id: req.params.id });
if (!order) return next();
await order.remove();

return res.status(200).send({ message: `Order was removed` });
}


module.exports.findOne = findOne
module.exports.findAll = findAll
module.exports.create = create
module.exports.update = update
module.exports.remove = remove
70 changes: 70 additions & 0 deletions backend/controllers/ProductsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
const Product = require('../db/models/product');

async function findOne(req, res, next) {
const product = await Product.findOne({ slug: req.params.slug }).populate('category','-slug -createdAt -updatedAt -__v');
if (!product) return next();
return res.status(200).send({ data: product });
}

async function findAll(req, res) {
const products = await Product.find().sort({ createdAt: 'desc' })
.populate('category','-slug -createdAt -updatedAt -__v');
return res.status(200).send({ data: products });
}

async function create(req, res) {
try {
const product = await new Product({
name: req.body.name,
description: req.body.description,
price: req.body.price,
weight: req.body.weight,
category: req.body.category,
}).save();

return res.status(201).send({ data: product, message: `Product was created` });

} catch (err) {
return res.status(400).send({message: `Product was not created, bad request`, error: err});
}
}

async function update(req, res, next) {
let product = await Product.findOne({ slug: req.params.slug });
if (!product) return res.status(404).send({message: `Product was not updated, bad request`});

const query = {
slug: req.params.slug
}
const update = {$set: {
name: req.body.name,
description: req.body.description,
price: req.body.price,
weight: req.body.weight,
category: req.body.categoryID
}}
const options = {runValidators: true}

try {
const updatedProduct = await Product.updateOne(query, update, options)
product = await Product.findOne({ slug: req.params.slug });
return res.status(200).send({ data: product, message: `Product was updated` });
} catch (err) {
return res.status(400).send({message: `Product was not created, bad request`, error: err});
}
}

async function remove(req, res, next) {
const product = await Product.findOne({ slug: req.params.slug });
if (!product) return next();
await product.remove();

return res.status(200).send({ message: `Product was removed` });
}


module.exports.findOne = findOne
module.exports.findAll = findAll
module.exports.create = create
module.exports.update = update
module.exports.remove = remove
23 changes: 0 additions & 23 deletions backend/data/db.js

This file was deleted.

24 changes: 24 additions & 0 deletions backend/db/models/category.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const mongoose = require('mongoose')
const URLSlugs = require('mongoose-url-slugs');

const predifinedNames = ['phone', 'pc', 'laptop', 'gps']

const categorySchema = new mongoose.Schema({
name: {
type: String,
lowercase: true,
required: true,
unique: true,
validate(value) {
if (!predifinedNames.includes(this.name)) {throw new Error('Use predifiend names!')}
}
},
}, {
timestamps: true
});

categorySchema.plugin(URLSlugs('name', { field: 'slug', update: true }));

const Category = mongoose.model('Category', categorySchema);

module.exports = Category
24 changes: 24 additions & 0 deletions backend/db/models/order-status.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const mongoose = require('mongoose')
const URLSlugs = require('mongoose-url-slugs');

const predifinedNames = ['not approved', 'approved', 'canceled', 'completed']

const ordersStatusSchema = new mongoose.Schema({
name: {
type: String,
lowercase: true,
required: true,
unique: true,
validate(value) {
if (!predifinedNames.includes(this.name)) {throw new Error('Use predifiend names!')}
}
},
}, {
timestamps: true
});

ordersStatusSchema.plugin(URLSlugs('name', { field: 'slug', update: true }));

const OrderStatus = mongoose.model('OrderStatus', ordersStatusSchema);

module.exports = OrderStatus
Loading

0 comments on commit 45819aa

Please sign in to comment.