Skip to content

Commit

Permalink
Merge pull request #65 from Arquisoft/develop
Browse files Browse the repository at this point in the history
Release of the First Version of the App (Master <-- Develop)
  • Loading branch information
lumialfe authored Mar 15, 2022
2 parents 6de2917 + b4fab92 commit 86e1030
Show file tree
Hide file tree
Showing 54 changed files with 6,055 additions and 1,353 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@ yarn-error.log*
#documentation build does not go into master
docs/build

.idea/
.idea/

.env
6 changes: 6 additions & 0 deletions package-lock.json

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

36 changes: 0 additions & 36 deletions restapi/api.ts

This file was deleted.

55 changes: 55 additions & 0 deletions restapi/controller/AuthController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Request, Response } from 'express';
import UserController from './UserController';
import UserModel from '../model/User';
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');



module.exports = {


register: async (req: Request, res: Response) => {

const salt = await bcrypt.genSalt(10);
const password = await bcrypt.hash(req.body.password, salt);

const { email, name, lastName, PODUrl } = req.body;
const user = new UserModel({email, name, lastName, password, PODUrl});

try {
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send(error);
}

},


login: async(req: Request, res: Response) => {
const { email, password } = req.body;
var userEmail = String(email);
const user = await UserModel.findOne({userEmail});
if(!user) {
return res.status(404).send('User not found');
}
const isMatch = await bcrypt.compare(password, user.password);
if(!isMatch) {
return res.status(401).send('Invalid password');
}

const token = jwt.sign({
name: user.email,
id: user._id
}, process.env.TOKEN_SECRET)

res.header('auth-token', token).json({
error: null,
data: {token}
}).send();
}
}

export default module.exports;

41 changes: 41 additions & 0 deletions restapi/controller/OrderController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Request, Response } from 'express';
import mongoose from 'mongoose';
import Order from '../model/Order';
import { Product } from '../model/Product';
import { ProductOrdered } from '../model/ProductOrdered';
import productController from './ProductController';


class OrderController {

public async saveOrder(req: Request, res: Response) {
const { userId, products} = req.body;
await Promise.all(products.map(async (productOrdered:ProductOrdered) => {
const p = await productController.getProductById(productOrdered.productId) as Product;
productOrdered.product = p;
console.log(productOrdered);
console.log(p);
productOrdered.price = p.price;
}));

const subTotal = products.reduce((acc:number, productOrdered:ProductOrdered) => acc + productOrdered.price * productOrdered.quantity, 0);
console.log("esto deberia ser lo ultimo" ,products)
const order = new Order( {userId, products, subTotal,deliveryPrice:0} );
order.save()
.then(() => res.status(201).json({ message: 'Order saved' }))
.catch(error => res.status(400).json({ error }));
}

public async getOrders(req: Request, res: Response) {
var orders = await Order.find({});
res.send(orders);
}

public async getOrderByUserId(req: Request, res: Response) {
const userId = req.params.userId;
var order = await Order.find({ userId: userId });
res.send(order);
}
}

export default new OrderController();
46 changes: 46 additions & 0 deletions restapi/controller/ProductController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Request, Response } from 'express';
import mongoose from 'mongoose';
import Product from '../model/Product';


class ProductController {


public saveProduct(req: Request, res: Response) {
const { name, description, price, image, category } = req.body;
const product
= new Product({name, description, price, image, category});
product.save()
.then(() => res.status(201).json({ message: 'Product saved' }))
.catch((error:any) => res.status(400).json({ error }));
}

public async getProducts(req: Request, res: Response) {
var products = await Product.find({});
res.send(products);
}

public async getProductsByIds(ids: string[]) {
var products = await Product.find({_id: {$in: ids}});
return products;
}

public async getProductById(id: string) { ///this GetProductById should be changed? I think we should use the one below.
var product = await Product.findOne({_id: id});
return product;
}

public async getProductWithId(req: Request, res: Response) {
const product = await Product.findOne({_id: req.params.id});
if (product) {
res.status(200).json(product);
console.log(product);
} else {
res.status(404).send({ message: 'Product Not Found' });
}

}
}

const productController = new ProductController();
export default productController;
39 changes: 39 additions & 0 deletions restapi/controller/UserController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Request, Response } from 'express';
import User,{UserModel} from '../model/User';
import mongoose from 'mongoose';




class UserController {



public async saveUser( user:UserModel) {
const userFound = User.findOne({email:user.email});
if(userFound != null){
throw new Error("User already exists");
}

user.save()
.catch((error:any) =>
{
throw new Error(error.message);
} );
}

public async getUsers(req: Request, res: Response) {
var users = await User.find({});
res.send(users);
}


public async getUserByEmail(req: Request, res: Response) {
const email=req.params.email;
var user = await User.findOne({email:email});
res.send(user);
}
}

export default new UserController();

20 changes: 20 additions & 0 deletions restapi/db/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//Connection to monogoDB
import mongoose from "mongoose";

import config from "./keys";

mongoose.set('toJSON', {
virtuals: true,
transform: (doc, converted) => {
delete converted._id;
}
});

mongoose.connect(`mongodb://${config.DB_USER}:${config.DB_PASSWORD}@${config.DB_URI}/${config.DB_NAME}`, {
authSource : "admin",


})
.then(db => console.log("DB is connected"))
.catch(err => console.error(err));

11 changes: 11 additions & 0 deletions restapi/db/keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import dotenv from 'dotenv';

dotenv.config();

export default {
DB_URI: process.env.DB_URI,
DB_NAME: process.env.DB_NAME,
DB_USER: process.env.DB_USER,
DB_PASSWORD: process.env.DB_PASSWORD,

};
33 changes: 33 additions & 0 deletions restapi/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { NextFunction } from "express";
import { Request, Response } from 'express';
import { UserModel } from "./../model/User";



const jwt = require('jsonwebtoken')

declare global {
namespace Express {
export interface Request {
user: UserModel;
}
}
}


class Auth{

public async verifyToken(req:Request, res:Response, next:NextFunction){
const token = req.header('auth-token');
if(!token) return res.status(401).send('Access denied. No token provided.');
try{
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = verified;
next();
}catch(err){
res.status(400).send('Invalid token.');
}
}
}

export default new Auth();
36 changes: 36 additions & 0 deletions restapi/model/Order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import moongose, { Schema,model } from 'mongoose';
import { Product } from './Product';
import { ProductOrdered } from './ProductOrdered';

const OrderSchema = new Schema({
userId: {
type: String,
required: true
},
//a list of products
products: {
type: Array,
required: true
},
subTotal: {
type: Number,
required: true
},
deliveryPrice: {
type: Number,
required: true
}
},{
timestamps: true
});

export interface Order extends moongose.Document {
userId: string;
products: Array<ProductOrdered>;
subTotal: number;
deliveryPrice: number;
}

export default model<Order>('Order', OrderSchema);


45 changes: 45 additions & 0 deletions restapi/model/Product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import moongose, { Schema,model } from 'mongoose';

const ProductSchema = new Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
min: 0,
required: true
},
description: {
type: String,
required: true
},

}, {
timestamps: true
});

export interface Product extends moongose.Document {
id: string;
name: string;
description: string;
price: number;
image: string;
category: string;
}

ProductSchema.method('toClient', function() {
var obj = this.toObject();

//Rename fields
obj.id = obj._id;
delete obj._id;

return obj;
});
// Ensure virtual fields are serialised.
ProductSchema.set('toJSON', {
virtuals: true
});

export default model<Product>('Product', ProductSchema);
Loading

0 comments on commit 86e1030

Please sign in to comment.