0% found this document useful (0 votes)
15 views26 pages

Diseño y Desarrollo de Servicios Web - Proyecto

This document outlines the design and development of web services for a project focused on creating an API for an e-commerce platform. It includes details on connecting to a database, implementing user authentication, and managing products and categories through various routes. The document also provides code snippets for setting up the server and defining routes for users, products, categories, and orders.

Uploaded by

adso sena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views26 pages

Diseño y Desarrollo de Servicios Web - Proyecto

This document outlines the design and development of web services for a project focused on creating an API for an e-commerce platform. It includes details on connecting to a database, implementing user authentication, and managing products and categories through various routes. The document also provides code snippets for setting up the server and defining routes for users, products, categories, and orders.

Uploaded by

adso sena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Diseño y Desarrollo de servicios web – proyecto.

Id Evidencia.

GA7-220501096-AA5-EV03

Aprendices.

German Lopera

Instructor.

Carlos Hernández

Centro de Desarrollo Agroindustrial y Empresarial


Sena Regional Cundinamarca, Villeta

Tecnología en Análisis y Desarrollo de Software.

Ficha :2758342

2025

INTRODUCCIÓN

Para que saber que es un API debes irte a las siglas que conforman el concepto de esta
herramienta tecnológica. El acrónimo API responde a la expresión anglosajona application

programming interface que en español quiere decir interfaz de programación de aplicaciones.

Se refiere a un conjunto de protocolos que se utiliza para integrar las funciones de distintas

aplicaciones y programas dentro de una página de Internet.


DESARROLLO

Se requiere realizar los servicios necesarios para cumplir con las características del software a
realizar para el proyecto formativo y la documentación de cada uno de los servicios.

CONEXIÓN A LA BASE DE DATOS

const express = require('express'); const app =


express();
const morgan = require('morgan');
const mongoose =
require('mongoose'); const cors =
require('cors');
require('dotenv/config');
const authJwt = require('./helpers/jwt');
const errorHandler = require('./helpers/error-handler');

app.use(cors());
app.options('*', cors())

//middleware app.use(express.json());
app.use(morgan('tiny'));
app.use(authJwt());
app.use('/public/uploads', express.static( dirname +
'/public/uploads')); app.use(errorHandler);

//Routes
const categoriesRoutes = require('./routes/categories'); const productsRoutes
= require('./routes/products'); const usersRoutes = require('./routes/users');
const ordersRoutes = require('./routes/orders'); const api =

process.env.API_URL;

app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/users`, usersRoutes); app.use(`$
{api}/orders`, ordersRoutes);

//Database mongoose.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'eshop-database'
})
.then(()=>{
console.log('Database Connection is ready...')
})
.catch((err)=> { console.log(err);
})

//Server app.listen(3000, ()=>{

console.log('server is running http://localhost:3000');


})
MÓDULO DE RUTAS USUARIOS

const {User} = require('../models/user');


const express = require('express');
const router = express.Router();
const bcrypt =
require('bcryptjs'); const jwt =
require('jsonwebtoken');

router.get(`/`, async (req, res) =>{


const userList = await User.find().select('-passwordHash');

if(!userList) {
res.status(500).json({success:
false})
}
res.send(userList);
})

router.get('/:id', async(req,res)=>{
const user = await User.findById(req.params.id).select('-passwordHash');

if(!user) {
res.status(500).json({message: 'The user with the given ID was
not found.'})
}
res.status(200).send(user);
})

router.post('/', async
(req,res)=>{ let user = new
User({
name: req.body.name,
email: req.body.email,
passwordHash: bcrypt.hashSync(req.body.password, 10),
phone: req.body.phone, isAdmin:
req.body.isAdmin, street: req.body.street,
apartment: req.body.apartment, zip:
req.body.zip,
city: req.body.city,
country: req.body.country,
})
user = await user.save();

if(!user)
return res.status(400).send('the user cannot be created!')

res.send(user);
})

router.put('/:id',async (req, res)=> {


const userExist = await User.findById(req.params.id); let newPassword
if(req.body.password) {
newPassword = bcrypt.hashSync(req.body.password, 10)
} else {
newPassword = userExist.passwordHash;
}

const user = await User.findByIdAndUpdate( req.params.id,


{
name: req.body.name, email:
req.body.email, passwordHash:
newPassword, phone:
req.body.phone, isAdmin:
req.body.isAdmin, street:
req.body.street,
apartment: req.body.apartment,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
},
{ new: true}
)

if(!user)
return res.status(400).send('the user cannot be created!')

res.send(user);
})

router.post('/login', async (req,res) => {


const user = await User.findOne({email: req.body.email}) const secret =
process.env.secret;
if(!user) {
return res.status(400).send('The user not found');
}

if(user && bcrypt.compareSync(req.body.password,


user.passwordHash)) { const token = jwt.sign(
{
userId: user.id,
isAdmin: user.isAdmin
},
secret,
{expiresIn : '1d'}
)
res.status(200).send({user: user.email , token: token})
} else {
res.status(400).send('password is wrong!');
}

})

router.post('/register', async
(req,res)=>{ let user = new User({
name: req.body.name,
email: req.body.email,
passwordHash: bcrypt.hashSync(req.body.password, 10),
phone: req.body.phone, isAdmin:
req.body.isAdmin, street: req.body.street,
apartment: req.body.apartment, zip:
req.body.zip,
city: req.body.city,
country: req.body.country,
})
user = await user.save();

if(!user)
return res.status(400).send('the user cannot be created!')

res.send(user);
})

router.delete('/:id', (req, res)=>{


User.findByIdAndRemove(req.params.id).then(user =>{
if(user) {
return res.status(200).json({success: true, message: 'the
user is
deleted!'})
} else {
return res.status(404).json({success: false , message: "user
not
found!"})
}
}).catch(err=>{
return res.status(500).json({success: false, error: err})
})
})

router.get(`/get/count`, async (req, res) =>{


const userCount = await User.countDocuments((count) => count)

if(!userCount) {
res.status(500).json({success: false})
}
res.send({
userCount: userCount
});
})

module.exports = router;
MÓDULO DE RUTAS – PRODUCTOS

const {Product} =
require('../models/product'); const express =
require('express');
const { Category } = require('../models/category'); const router =
express.Router();
const mongoose = require('mongoose'); const multer =
require('multer');

const FILE_TYPE_MAP =
{ 'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
}

const storage = multer.diskStorage({ destination: function


(req, file, cb) {
const isValid = FILE_TYPE_MAP[file.mimetype];
let uploadError = new Error('invalid image type');

if(isValid) {
uploadError = null
}
cb(uploadError, 'public/uploads')
},
filename: function (req, file, cb) {

const fileName = file.originalname.split(' ').join('-'); const extension =


FILE_TYPE_MAP[file.mimetype]; cb(null, `${fileName}-${Date.now()}.$
{extension}`)
}
})

const uploadOptions = multer({ storage: storage })

router.get(`/`, async (req, res)


=>{ let filter = {};
if(req.query.categories)
{
filter = {category: req.query.categories.split(',')}
}

const productList = await Product.find(filter).populate('category');

if(!productList) {
res.status(500).json({success:
false})
}
res.send(productList);
})
router.get(`/:id`, async (req, res) =>{ const product = await
Product.findById(req.params.id).populate('category');

if(!product) {
res.status(500).json({success:
false})
}
res.send(product);
})

router.post(`/`, uploadOptions.single('image'), async (req, res) =>{ const category = await


Category.findById(req.body.category); if(!category) return res.status(400).send('Invalid
Category')

const file = req.file;


if(!file) return res.status(400).send('No image in the request')

const fileName = file.filename


const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`; let product = new Product({
name: req.body.name,
description: req.body.description, richDescription:
req.body.richDescription, image: `${basePath}${fileName}`,//
"http://localhost:3000/public/upload/image-2323232" brand:
req.body.brand,
price: req.body.price,
category: req.body.category, countInStock:
req.body.countInStock, rating: req.body.rating,
numReviews: req.body.numReviews,
isFeatured: req.body.isFeatured,
})

product = await product.save();

if(!product)
return res.status(500).send('The product cannot be created')

res.send(product);
})

router.put('/:id',async (req, res)=> { if(!


mongoose.isValidObjectId(req.params.id)) {
return res.status(400).send('Invalid Product Id')
}
const category = await Category.findById(req.body.category); if(!category) return
res.status(400).send('Invalid Category')
const product = await Product.findByIdAndUpdate( req.params.id,
{
name: req.body.name,
description: req.body.description, richDescription:
req.body.richDescription, image: req.body.image,
brand: req.body.brand, price:
req.body.price, category:
req.body.category,
countInStock: req.body.countInStock,
rating: req.body.rating, numReviews:
req.body.numReviews, isFeatured:
req.body.isFeatured,
},
{ new: true}
)

if(!product)
return res.status(500).send('the product cannot be updated!')

res.send(product);
})

router.delete('/:id', (req, res)=>{


Product.findByIdAndRemove(req.params.id).then(product =>{
if(product) {
return res.status(200).json({success: true, message: 'the
product is deleted!'})
} else {
return res.status(404).json({success: false , message:
"product not found!"})
}
}).catch(err=>{
return res.status(500).json({success: false, error: err})
})
})

router.get(`/get/count`, async (req, res) =>{


const productCount = await Product.countDocuments((count) => count)

if(!productCount) {
res.status(500).json({success:
false})
}
res.send({
productCount: productCount
});
})
router.get(`/get/featured/:count`, async (req, res) =>{ const count =
req.params.count ? req.params.count : 0
const products = await Product.find({isFeatured: true}).limit(+count);

if(!products) {
res.status(500).json({success:
false})
}
res.send(products);
})

router.put(
'/gallery-images/:id',
uploadOptions.array('images', 10),
async (req, res)=> {
if(!mongoose.isValidObjectId(req.params.id)) {
return res.status(400).send('Invalid Product Id')
}
const files = req.files let
imagesPaths = []; const basePath
=
`${req.protocol}://${req.get('host')}/public/uploads/`;

if(files) {
files.map(file =>{
imagesPaths.push(`${basePath}${file.filename}`);
})
}

const product = await Product.findByIdAndUpdate( req.params.id,


{
images: imagesPaths
},
{ new: true}
)

if(!product)
return res.status(500).send('the gallery cannot be updated!')

res.send(product);
}
)

module.exports = router;
MÓDULO DE RUTAS – CATEGORÍAS

const {Category} =
require('../models/category'); const express =
require('express');
const router = express.Router();

router.get(`/`, async (req, res) =>{


const categoryList = await Category.find();

if(!categoryList) {
res.status(500).json({success:
false})
}
res.status(200).send(categoryList);
})

router.get('/:id', async(req,res)=>{
const category = await Category.findById(req.params.id);

if(!category) {
res.status(500).json({message: 'The category with the given ID
was not found.'})
}
res.status(200).send(category);
})

router.post('/', async
(req,res)=>{ let category =
new Category({
name: req.body.name, icon:
req.body.icon, color:
req.body.color
})
category = await category.save();

if(!category)
return res.status(400).send('the category cannot be created!')

res.send(category);
})

router.put('/:id',async (req, res)=> {


const category = await Category.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
icon: req.body.icon || category.icon,
color: req.body.color,
},
{ new: true}
)

if(!category)
return res.status(400).send('the category cannot be created!')

res.send(category);
})

router.delete('/:id', (req, res)=>{ Category.findByIdAndRemove(req.params.id).then(category =>{


if(category) {
return res.status(200).json({success: true, message: 'the category is deleted!'})
} else {
return res.status(404).json({success: false , message: "category not found!"})
}
}).catch(err=>{
return res.status(500).json({success: false, error: err})
})
})

module.exports = router;
MÓDULO DE RUTAS – SOLICITUDES

const {Order} =
require('../models/order'); const express
= require('express');
const { OrderItem } = require('../models/order-item'); const router =
express.Router();

router.get(`/`, async (req, res) =>{


const orderList = await Order.find().populate('user', 'name').sort({'dateOrdered': -1});

if(!orderList) {
res.status(500).json({success:
false})
}
res.send(orderList);
})

router.get(`/:id`, async (req, res) =>{


const order = await Order.findById(req.params.id)
.populate('user', 'name')
.populate({
path: 'orderItems', populate: {
path : 'product', populate: 'category'}
});

if(!order) {
res.status(500).json({success: false})
}
res.send(order);
})

router.post('/', async (req,res)=>{


const orderItemsIds = Promise.all(req.body.orderItems.map(async
(orderItem) =>{
let newOrderItem = new OrderItem({ quantity:
orderItem.quantity, product: orderItem.product
})

newOrderItem = await newOrderItem.save();

return newOrderItem._id;
}))
const orderItemsIdsResolved = await orderItemsIds;

const totalPrices = await Promise.all(orderItemsIdsResolved.map(async


(orderItemId)=>{
const orderItem = await
OrderItem.findById(orderItemId).populate('product', 'price');
const totalPrice = orderItem.product.price * orderItem.quantity;
return totalPrice
}))

const totalPrice = totalPrices.reduce((a,b) => a +b , 0);

let order = new Order({


orderItems: orderItemsIdsResolved, shippingAddress1:
req.body.shippingAddress1, shippingAddress2:
req.body.shippingAddress2, city: req.body.city,
zip: req.body.zip, country:
req.body.country, phone:
req.body.phone, status:
req.body.status, totalPrice:
totalPrice, user: req.body.user,
})
order = await order.save();

if(!order)
return res.status(400).send('the order cannot be created!')

res.send(order);
})

router.put('/:id',async (req, res)=> {


const order = await Order.findByIdAndUpdate( req.params.id,
{
status: req.body.status
},
{ new: true}
)

if(!order)
return res.status(400).send('the order cannot be update!')

res.send(order);
})

router.delete('/:id', (req, res)=>{


Order.findByIdAndRemove(req.params.id).then(async order =>{
if(order) {
await order.orderItems.map(async orderItem => {
await OrderItem.findByIdAndRemove(orderItem)
})
return res.status(200).json({success: true, message: 'the
order is
deleted!'})
} else {
return res.status(404).json({success: false , message: "order
not
found!"})
}
}).catch(err=>{
return res.status(500).json({success: false, error: err})
})
})

router.get('/get/totalsales', async (req, res)=> { const totalSales= await


Order.aggregate([
{ $group: { _id: null , totalsales : { $sum : '$totalPrice'}}}
])

if(!totalSales) {
return res.status(400).send('The order sales cannot be
generated')
}

res.send({totalsales: totalSales.pop().totalsales})
})

router.get(`/get/count`, async (req, res) =>{


const orderCount = await Order.countDocuments((count) => count)

if(!orderCount) {
res.status(500).json({success:
false})
}
res.send({
orderCount: orderCount
});
})

router.get(`/get/userorders/:userid`, async (req, res) =>{ const userOrderList =


await Order.find({user:
req.params.userid}).populate({
path: 'orderItems', populate: {
path : 'product', populate: 'category'}
}).sort({'dateOrdered': -1});

if(!userOrderList) {
res.status(500).json({success:
false})
}
res.send(userOrderList);
})

module.exports = router;
PRUEBAS EN POSTMAN

Get Productos
POST PRODUCTOS
CONEXIÓN A LA BASE DE DATOS
CONCLUSIÓN

Se pudo comprobar la utilidad que ofrece una webService para realizar pruebas de

funcionamiento de nuestro sistema al momento de procesar peticiones por parte del

usuario, sin la necesidad de contar con el frontend, además de ofrecer información de

nuestro sistema para que sea utilizado por otras aplicaciones sin la necesidad de requerir

autenticaciones, permitiendo controlar el tipo de información que queremos ofrecer.


Bibliografía.

https://zajuna.sena.edu.co/Repositorio/Titulada/institution/SENA/Tecnologia/228118/Contenido/
OVA/CF33/index.html#/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy