Skip to content

Commit

Permalink
feat: refactor complete api
Browse files Browse the repository at this point in the history
  • Loading branch information
Beor18 committed Aug 1, 2019
1 parent e298b4b commit 37bc1c2
Show file tree
Hide file tree
Showing 11 changed files with 5,790 additions and 4,734 deletions.
40 changes: 25 additions & 15 deletions README.md
Expand Up @@ -4,7 +4,7 @@

Tener instalado [Node.js](https://nodejs.org/) y [MongoDB](https://www.mongodb.com/es).

Set variable de entorno de MongoDb:
Setee variable de entorno de MongoDb:

```sh
$ export MONGODB_URL="mongodb://..."
Expand Down Expand Up @@ -50,26 +50,36 @@ $ npm test
/api/users/register (POST)

/api/perfil (GET)
/api/productos (GET)
/api/productos (POST)
/api/productos/:id (GET)
/api/productos/:id (PUT)
/api/productos/:id (DELETE)
/api/peliculas (GET)
/api/peliculas (POST)
/api/peliculas/:id (GET)
/api/peliculas/:id (PUT)
/api/peliculas/:id (DELETE)
```
#### Modelo User

```
name: tipo String - requerido
email: tipo String - requerido
password: tipo String - requerido
avatar: tipo String
date: tipo Date
name: String - requerido
email: String - requerido
password: String - requerido
avatar: String
date: Date
```

#### Modelo Producto
#### Modelo Peliculas

```
titulo: tipo String
autor: tipo String
foto: tipo: String
name: String
description: String
stars: Array
year: Number
gender: String
categories: Array
```

### Modelo Categorias

```
name: String
date: Date
```
34 changes: 12 additions & 22 deletions app.js
Expand Up @@ -3,24 +3,19 @@ const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const config = require('./config/db');
const path = require('path');
const cors = require('cors');
// const session = require('express-session'); (OPCIONAL)
// const MongoStore = require('connect-mongo')(session);

const rutasSeguras = require('./routes/rutas-seguras');
const users = require('./routes/user');

const { getLogger, logHandler, terminate } = require('@jwt/utils')
const { getLogger, logHandler, terminate } = require('@jwt/utils');
require('./config/passport')(passport);

const app = express();

app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');

next();
});
const log = getLogger(__dirname, __filename)
const PORT = process.env.PORT || 5000;

// Manejo de sesiones (OPCIONAL)
// app.use(session({
Expand All @@ -32,27 +27,22 @@ app.use((req, res, next) => {
// })
// }));

// Dentro de una funcion en algun controller agregar esta linea:
// req.session.cuenta = req.session.cuenta ? req.session.cuenta + 1 : 1

app.use(cors());
app.use(passport.initialize());
require('./config/passport')(passport);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(logHandler);
app.use(express.static(path.join(__dirname, 'public')));


app.use('/api/users', users);
app.use('/api', passport.authenticate('jwt', { session: false }), rutasSeguras);

app.get('/', function(req, res) {
res.send('Hola');
});
app.disable('etag');
app.disable('x-powered-by');

const log = getLogger(__dirname, __filename)
const PORT = process.env.PORT || 5000;
app.get('/', (req, res) => {
res.send('Hola api rest de Peliculas! creado por Fernando López y Logan');
});

if (!module.parent) {
app.listen(PORT, () => {
Expand Down
120 changes: 120 additions & 0 deletions controllers/pelicula.controller.js
@@ -0,0 +1,120 @@
const Pelicula = require('../models/Pelicula');
const passport = require('passport');

const { getLogger } = require('@jwt/utils')
const log = getLogger(__dirname, __filename)


async function getPeliculas(req, res, next) {
try {
let perPage = req.query.perPage || 9;
perPage = Number(perPage);

let page = req.query.page || 1;
page = Number(page);

await Pelicula
.find({})
.skip((perPage * page) - perPage)
.limit(perPage)
.exec((err, peliculas) => {
Pelicula.countDocuments((err, count) => {
if (err) return next(err);
res.status(200).json({
status: 'Api funcionando',
peliculas,
total: count,
resultados: perPage
});
});
});
} catch (err) {
log.error('Ups hubo un error al mostrar las peliculas! ' + err);
}
}

async function getPeliculaPorId(req, res) {
try {
await Pelicula.findById(req.params.id, function(err, pelicula) {
if (pelicula === null) {
return res.status(404).json({mensaje: 'Pelicula no encontrada!'});
}else {
res.status(200).json({
status: 'Api funcionando',
pelicula
});
}
});
} catch (err) {
log.error('Ups hubo un error al mostrar la Pelicula! ' + err);
}
}

async function modificarPelicula(req, res) {
try {
const { id } = req.params;
await Pelicula.update({ _id: id }, req.body);
res.status(200).json('Pelicula Modificada con éxito!')
log.warn('Pelicula Modificada con éxito!');
} catch (err) {
log.error('Ups hubo un error al modificar la pelicula! ' + err);
}

}

async function postPelicula(req, res) {
try {
const pelicula = new Pelicula(req.body);
await pelicula.save(() => {
res.status(201).json("Pelicula agregada con éxito!");
log.info("Peliculaagregada con éxito!");
});
} catch (err) {
log.error('Ups hubo un error al agregar la pelicula! ' + err);
}
}

async function deletePelicula(req, res) {
try {
await Pelicula.findByIdAndRemove(req.params.id, (err) => {
if (err) {
return res.send(err);
} else {
res.status(200).json('Pelicula Borrada con éxito!');
log.error('Pelicula Borrada con éxito!')
}
});
} catch (err) {
log.error('Ups hubo un error al borrar la pelicula! ' + err);
}
}

async function filtroEstrella(req, res) {
try {
await Pelicula.find({'stars': req.params.stars}, (err, pelicula) => {
if (pelicula <= null) {
return res.status(404).json({
mensaje: 'No encontrado!',
peliculas: pelicula,
err
});
} else {
res.status(200).json({
status: 'Filtrado por estrella OK',
peliculas: pelicula
});
}
})
} catch (err) {
log.error('Ups hubo un error!');
}
}

module.exports = {
getPeliculas,
getPeliculaPorId,
modificarPelicula,
postPelicula,
deletePelicula,
filtroEstrella
};
1 change: 0 additions & 1 deletion controllers/perfil.controller.js
Expand Up @@ -6,7 +6,6 @@ const log = getLogger(__dirname, __filename)

async function getPerfil(req, res, next) {
try {
let token = req.query.secret_token;
return res.status(200).json({
id: req.user.id,
name: req.user.name,
Expand Down
101 changes: 0 additions & 101 deletions controllers/producto.controller.js

This file was deleted.

26 changes: 26 additions & 0 deletions models/Pelicula.js
@@ -0,0 +1,26 @@
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const PeliculaSchema = new Schema({
name: { type: String },
description: { type: String },
stars: { type: Array },
year: { type: Number },
gender: { type: String },
categories: [{ type: Schema.Types.ObjectId, ref: 'Categorie' }]

});

const CategorieSchema = new Schema({
name: { type: String },
date: { type: Date, default: Date.now }
});

const Pelicula = mongoose.model('Pelicula', PeliculaSchema);
const Categorie = mongoose.model('Categorie', CategorieSchema);

module.exports = {
Pelicula,
Categorie
};

0 comments on commit 37bc1c2

Please sign in to comment.