Skip to content

Commit

Permalink
Categorias y Productos
Browse files Browse the repository at this point in the history
  • Loading branch information
rjvelazco committed Nov 26, 2020
1 parent 0723819 commit 7625e42
Show file tree
Hide file tree
Showing 8 changed files with 472 additions and 3 deletions.
2 changes: 1 addition & 1 deletion server/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ process.env.NODE_ENV = process.env.NODE_ENV || 'dev';
// Vencmiento del Token
// =============================

process.env.CADUCIDAD_TOKEN = 60 * 60 * 24 * 30;
process.env.CADUCIDAD_TOKEN = '48h';

// =============================
// SEED de autenticacion
Expand Down
21 changes: 21 additions & 0 deletions server/models/categoria.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;

let categoriaSchema = new Schema({

descripcion: {
type: String,
unique: true,
required: [true, 'La descripcion del producto es requerida']
},
usuario: {
type: Schema.Types.ObjectId,
ref: 'Usuario'
}

});

categoriaSchema.plugin(uniqueValidator, { message: 'Errpr, {PATH} debe de ser unico' });

module.exports = mongoose.model('Categoria', categoriaSchema);
15 changes: 15 additions & 0 deletions server/models/producto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var productoSchema = new Schema({
nombre: { type: String, required: [true, 'El nombre es necesario'] },
precioUni: { type: Number, required: [true, 'El precio únitario es necesario'] },
descripcion: { type: String, required: false },
disponible: { type: Boolean, required: true, default: true },
categoria: { type: Schema.Types.ObjectId, ref: 'Categoria', required: true },
usuario: { type: Schema.Types.ObjectId, ref: 'Usuario' }
});


module.exports = mongoose.model('Producto', productoSchema);
2 changes: 1 addition & 1 deletion server/models/usuario.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator')
const uniqueValidator = require('mongoose-unique-validator');

let rolesValidos = {
values: ['ADMIN_ROLE', 'USER_ROLE'],
Expand Down
164 changes: 164 additions & 0 deletions server/routes/categoria.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
const express = require('express');
const _ = require('underscore');

const { verificaToken, verificaAdmin_Role } = require('../middlewares/authentication');

const app = express();

let Categoria = require('../models/categoria');

// ============================
// Mostrar todas las categorias
// ============================
app.get('/categoria', verificaToken, (req, res) => {
let from = req.query.from || 0;
let limit = req.query.limit || 10;

from = Number(from);
limit = Number(limit);

Categoria.find({})
.sort('descripcion')
.skip(from)
.limit(limit)
.populate('usuario', 'nombre email')
.exec((err, categoriasDB) => {
if (err) {
return res.status(400).json({
ok: false,
err
})
};
Categoria.countDocuments({}, (err, count) => {
res.json({
ok: true,
categorias: categoriasDB,
cuantos: count
});
})

});
});

// ============================
// Mostrar categoria ID
// ============================
app.get('/categoria/:id', verificaToken, (req, res) => {

let id = req.params.id;
Categoria.findById(id, (err, categoriaDB) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
};

if (!categoriaDB) {
return res.status(400).json({
ok: false,
err: {
message: 'El ID no pertenece a ninguna categoria'
}
});
};

res.json({
ok: true,
categoria: categoriaDB
})

})

});

// ============================
// Crear nueva categoria
// ============================
app.post('/categoria', [verificaToken, verificaAdmin_Role], (req, res) => {
// Regresa la nueva categoria

const body = req.body;
const usuario = req.usuario

let categoria = new Categoria({
descripcion: body.descripcion,
usuario: usuario._id
});

categoria.save((err, categoriaDB) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
};
if (!categoriaDB) {
return res.status(400).json({
ok: false,
err
});
}
res.json({
ok: true,
categoria: categoriaDB
})
})
});

// ============================
// Actualizar una categoria
// ============================
app.put('/categoria/:id', [verificaToken, verificaAdmin_Role], (req, res) => {

let id = req.params['id'];
let body = _.pick(req.body, ['descripcion']);

let opc = { new: true, runValidators: true, context: 'query' }

Categoria.findByIdAndUpdate(id, body, opc, (err, categoriaDB) => {
if (err) {
return res.status(400).json({
ok: false,
err
});
};

res.json({
ok: true,
categoria: categoriaDB
})
})
});


// ============================
// Crear nueva categoria
// ============================
app.delete('/categoria/:id', [verificaToken, verificaAdmin_Role], (req, res) => {
// Solo un administrador puede borrar categoria
const id = req.params.id;

Categoria.findByIdAndDelete(id, (err, categoriaDB) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
};
if (!categoriaDB) {
return res.status(400).json({
ok: false,
err: {
message: 'Categoria no encontrado'
}
})
}
res.json({
ok: true,
categoria: categoriaDB
})
})
});

module.exports = app;
3 changes: 3 additions & 0 deletions server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ const app = express();

app.use(require('./usuario'));
app.use(require('./login'));
app.use(require('./categoria'));
app.use(require('./producto'));
// app.use(require('./producto'));

module.exports = app;
1 change: 0 additions & 1 deletion server/routes/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ async function verify(token) {
});
const payload = ticket.getPayload();

console.log(payload);
return {
nombre: payload.name,
email: payload.email,
Expand Down
Loading

0 comments on commit 7625e42

Please sign in to comment.