Skip to content

Commit

Permalink
Merge pull request #23 from rpalaciosg/refactor-ddd
Browse files Browse the repository at this point in the history
  • Loading branch information
rpalaciosg authored Aug 23, 2021
2 parents 135c888 + 8d0ecdc commit 0082df2
Show file tree
Hide file tree
Showing 12 changed files with 931 additions and 838 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use strict";

let Anuncio = require("../models/Anuncio");
let Anuncio = require("./model");

// var anuncioController = {};

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
'use strict';
"use strict";

const express = require('express');
const express = require("express");
const router = express.Router();

const anuncioController = require('../../controllers/AnuncioController');
const Anuncio = require('../../models/Anuncio');
const anuncioController = require("../../apiServices/anuncios/controller");
const Anuncio = require("../../apiServices/anuncios/model");

/**
* GET /anuncios
* Devuelve una lista de anuncios
* http://localhost:3000/apiv1/anuncios
*/
router.get('/', async (req, res, next) => {
router.get("/", async (req, res, next) => {
try {
const skip = parseInt(req.query.start);
const limit = parseInt(req.query.limit);
Expand All @@ -34,7 +34,7 @@ router.get('/', async (req, res, next) => {
// const cursor = db.collection('anuncios').find({ tags: { $in: ['work','stylelife']}});
if (tags !== "") {
const extTags = tags.split(" ");
filter.tags = { '$in': extTags };
filter.tags = { "$in": extTags };
}

if (venta) {
Expand All @@ -49,12 +49,12 @@ router.get('/', async (req, res, next) => {
res.status(422).json({success: false, error:"El primero parámetro del rango de precio debe ser menor"});
return;
}
filter.precio = { '$gte': extPrecio[0], '$lte': extPrecio[1] };
filter.precio = { "$gte": extPrecio[0], "$lte": extPrecio[1] };
} else if (patPreMayor.test(precio)) {
filter.precio = { '$gte': extPrecio[0] };
filter.precio = { "$gte": extPrecio[0] };
console.log("arma precio mayor -->", filter.precio);
} else if (patPreMenor.test(precio)) {
filter.precio = { '$lte': parseInt(extPrecio[1]) };
filter.precio = { "$lte": parseInt(extPrecio[1]) };
console.log("arma precio menor -->", filter.precio);
} else if (patPreIgual.test(precio)) {
filter.precio = parseInt(extPrecio[0]);
Expand All @@ -63,7 +63,7 @@ router.get('/', async (req, res, next) => {
}

if (nombre) {
filter.nombre = {$regex: new RegExp('^' + nombre + '.*', 'i')};
filter.nombre = {$regex: new RegExp("^" + nombre + ".*", "i")};
}

const anuncios = await anuncioController.listaAnuncios({filter:filter, skip, limit, fields, sort});
Expand All @@ -78,7 +78,7 @@ router.get('/', async (req, res, next) => {
* Obtiene el listado de tags existentes
* http://localhost:3000/apiv1/anuncios/tags
*/
router.get('/tags', async (req, res, next) => {
router.get("/tags", async (req, res, next) => {
try {
const tagList = await anuncioController.listaTags();
res.json({ success: true, results: tagList });
Expand All @@ -92,7 +92,7 @@ router.get('/tags', async (req, res, next) => {
* Obtiene un agente mediante el :id
* http://localhost:3000/apiv1/anuncios/:id
*/
router.get('/:id', async(req, res, next) => {
router.get("/:id", async(req, res, next) => {
try {
const _id = req.params.id;
const anuncio = await anuncioController.consultarUnAnuncio(_id);
Expand All @@ -110,7 +110,7 @@ router.get('/:id', async(req, res, next) => {
* Crea un anuncio
* http://localhost:3000/apiv1/anuncios
*/
router.post('/', async (req, res, next) => {
router.post("/", async (req, res, next) => {
try {
const data = req.body;
const anuncio = new Anuncio(data);
Expand All @@ -126,7 +126,7 @@ router.post('/', async (req, res, next) => {
* Actualiza un anuncio
* http://localhost:3000/apiv1/anuncios/:id
*/
router.put('/:id', async(req, res, next) => {
router.put("/:id", async(req, res, next) => {
try {
const _id = req.params.id;
const data = req.body;
Expand Down
72 changes: 22 additions & 50 deletions nodepop/app.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,46 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const { error404Handler,generalErrorHandler } = require("./middleware");
const routes = require("./routes");

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', require('ejs').__express);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "html");
app.engine("html", require("ejs").__express);

// Middlewares
app.use(logger('dev'));
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')));
app.use(express.static(path.join(__dirname, "public")));

/**
* Conexión a la base de datos
*/
require('./lib/connectDB');
require('./models/Anuncio');
require('./controllers/AnuncioController');
require("./services/mongoDB");
// require("./apiServices/anuncios/model");
// require("./apiServices/anuncios/controller");

/**
* Rutas de mi API
*/
app.use('/apiv1/anuncios', require('./routes/apiv1/anuncios'));
// app.use("/apiv1/anuncios", require("./routes/apiv1/routes"));
app.use("/apiv1/", routes);

// Variables goblales para vistas
app.locals.title = 'NodePop';
// Variables globales para vistas
app.locals.title = "NodePop";

/**
* Rutas de mi aplicación web
*/
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// comprueba error de validación
if (err.array) {
err.status = 422;
const errInfo = err.array({ onlyFirstError: true })[0];
err.message = isAPI(req)
? {message: 'Not valid', errors: err.mapped()}
: `Not valid - ${errInfo.param} ${errInfo.msg}`;
}
res.status(err.status || 500);
if(isAPI(req)) {
res.json({ success: false, error: err.message});
return;
}
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.render('error');
});

// función para saber si es una petición a un API
function isAPI(req) {
return req.originalUrl.indexOf('/api') === 0;
}
app.use("/",require("./routes/index"));
app.use(error404Handler); // catch 404 and forward to error handler
app.use(generalErrorHandler); // error handler

module.exports = app;
4 changes: 2 additions & 2 deletions nodepop/install_db.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ const fs = require("fs");
const fsPromises = fs.promises;

const mongoose = require("mongoose");
const conn = require("./lib/connectDB");
const conn = require("./services/mongoDB");
const Anuncio = require("./models/Anuncio");

const file = "./data/anuncios.json";
const file = "./services/data/anuncios.json";
const data = JSON.parse(fs.readFileSync(file,"utf-8"));

// conectar
Expand Down
31 changes: 31 additions & 0 deletions nodepop/middleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use strict";

module.exports.error404Handler = function (req, res, next) {
next(createError(404));
};

module.exports.generalErrorHandler = function(err, req, res, next) {
// comprueba error de validación
if (err.array) {
err.status = 422;
const errInfo = err.array({ onlyFirstError: true })[0];
err.message = isAPI(req)
? {message: "Not valid", errors: err.mapped()}
: `Not valid - ${errInfo.param} ${errInfo.msg}`;
}
res.status(err.status || 500);
if(isAPI(req)) {
res.json({ success: false, error: err.message});
return;
}
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.render("error");
};

// función para saber si es una petición a un API
function isAPI(req) {
return req.originalUrl.indexOf("/api") === 0;
}
Loading

0 comments on commit 0082df2

Please sign in to comment.