Skip to content

Commit

Permalink
melhorias no codigo com eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
joaopaulogse committed Nov 24, 2017
1 parent 53c701b commit df77245
Show file tree
Hide file tree
Showing 14 changed files with 235 additions and 236 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ coverage
.env
*.log
data
*.pem
*.pem
.idea
63 changes: 32 additions & 31 deletions src/api/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,53 @@
// sequelize const User = require("../models/user.model");
const HttpStatus = require("http-status");
//mongodb
const Users = require('../models/users.model');
// mongodb
const Users = require("../models/users.model");

exports.create = function(req, res) {
const { username, password, email, tipo } = req.body;
Users.create({ username, password, email, tipo }).then(users => {
res.setHeader('Content-Type', 'application/json')
res.status(HttpStatus.OK).send(users)
Users.create({ username, password, email, tipo })
.then((users) => {
res.setHeader("Content-Type", "application/json");
res.status(HttpStatus.OK).send(users);
})
.catch(err => {
.catch((err) => {
console.error(err.message);
res.status(HttpStatus.BAD_REQUEST).send(err);
})
}
});
};
exports.listarUsuarios = (req, res) => {
Users.find().then(users => {
res.setHeader('Content-Type', 'application/json')
res.status(HttpStatus.OK).json(users);
})
}
exports.loadUser = (req, res, next) => {
Users.find().then((users) => {
res.setHeader("Content-Type", "application/json");
res.status(HttpStatus.OK).json(users);
});
};
exports.loadUser = (req, res) => {
Users.findById(req.params.id)
.then(user => res.status(HttpStatus.OK).send(user))
.catch(err => {
.catch((err) => {
res.status(HttpStatus.NOT_FOUND).send("não achado!");
console.error(err.message);
})
}
exports.update = (req, res, next) => {
});
};
exports.update = (req, res) => {
const { username, email, tipo, password } = req.body;
Users.findByIdAndUpdate(req.params.id, { $set: { username, password, email, tipo } }, {new:true})
.then(user => {
res.setHeader('Content-Type', 'application/json')
res.status(HttpStatus.CREATED).send(user)
Users.findByIdAndUpdate(req.params.id, { $set: { username, password, email, tipo } }, { 'new' : true })
.then((user) => {
res.setHeader("Content-Type", "application/json");
res.status(HttpStatus.CREATED).send(user);
})
.catch(err => {
.catch((err) => {
res.status(HttpStatus.BAD_REQUEST).send("Não foi alterado!");
console.error(err.message);
})
}
exports.deleteUser = (req, res, next) => {
});
};
exports.deleteUser = (req, res) => {
Users.findByIdAndRemove(req.params.id)
.then(() => {
res.status(HttpStatus.CREATED).send('Deletado com Sucesso!')
res.status(HttpStatus.CREATED).send("Deletado com Sucesso!");
})
.catch(err => {
res.status(HttpStatus.BAD_REQUEST).send("não foi possivel deletar!")
.catch((err) => {
res.status(HttpStatus.BAD_REQUEST).send("não foi possivel deletar!");
console.error(err.message);
})
}
});
};
12 changes: 6 additions & 6 deletions src/api/middleware/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ const HttpStatus = require("http-status");

exports.error404 = (req, res, next) => {
res.status(HttpStatus.NOT_FOUND).json({
error: "url not found"
error: "url not found",
});
next();
}
};

exports.error400 = (err, req, res, next) =>{
exports.error400 = (err, req, res, next) => {
res.status(HttpStatus.BAD_REQUEST).json({
error: err.errors,
status: err.status,
statusText: err.statusText
statusText: err.statusText,
})
next()
}
next();
};
101 changes: 50 additions & 51 deletions src/api/models/UserSchema.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,60 @@
const {
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLBoolean,
GraphQLInt
} = require('graphql');
GraphQLInt,
} = require("graphql");

const User = require('./users.model');
const User = require("./users.model");

var users = new GraphQLObjectType({
name: 'user',
description: 'Lista de Usuários',
fields: () => ({
_id:{
type:(GraphQLInt),
description:'Identificador único do usuário'
},
username: {
type: GraphQLString,
description: 'Nome do Usuário.',
},
email: {
type: GraphQLString,
description: 'Email do Usuário'
},
password:{
type:GraphQLString,
description:'Senha do Usuário'
},
createdAt:{
type:GraphQLString,
description:'Data de criação'
},
tipo:{
type:GraphQLString
}
})
const users = new GraphQLObjectType({
name: "user",
description: "Lista de Usuários",
fields: () => ({
_id: {
type: (GraphQLInt),
description: "Identificador único do usuário",
},
username: {
type: GraphQLString,
description: "Nome do Usuário.",
},
email: {
type: GraphQLString,
description: "Email do Usuário",
},
password: {
type: GraphQLString,
description: "Senha do Usuário",
},
createdAt: {
type: GraphQLString,
description: "Data de criação",
},
tipo: {
type: GraphQLString,
},
}),
});

let schema = new GraphQLSchema({
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name:'users',
fields:{
name: "users",
fields: {
user: {
type:new GraphQLList(users),
resolve:()=>{
return new Promise((resolve, reject)=>{
User.find().then(user=>{
resolve(user);
}).catch(err=>{
reject(err)
})
})
}
}
}
})
})
module.exports = { schema };
type: new GraphQLList(users),
resolve: () =>
new Promise((resolve, reject) => {
User.find()
.then((user) => {
resolve(user);
}).catch((err) => {
reject(err);
});
}),
},
},
}),
});
module.exports = { schema };
32 changes: 16 additions & 16 deletions src/api/models/user.model.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,51 @@
const { sequelize, DataTypes } = require('../../config/database');
const bcrypt = require('bcrypt-nodejs');
const { sequelize, DataTypes } = require("../../config/database");
const bcrypt = require("bcrypt-nodejs");


const User = sequelize.define('users', {
const User = sequelize.define("users", {
username: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
}
notEmpty: true,
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
}
notEmpty: true,
},
},
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
notEmpty: true,
},
set(email) {
this.setDataValue("email", email.toLowerCase());
}
},
},
tipo: {
type: DataTypes.ENUM(['admin', 'user']),
defaultValue: 'user',
type: DataTypes.ENUM(["admin", "user"]),
defaultValue: "user",
set(tipo) {
this.setDataValue('tipo', tipo.toLowerCase());
this.setDataValue("tipo", tipo.toLowerCase());
},
comment: 'Tipo do usuario!',
comment: "Tipo do usuario!",
},
}, {
hooks: {
beforeCreate: user => {
beforeCreate: (user) => {
const salt = bcrypt.genSaltSync();
user.set("password", bcrypt.hashSync(user.password, salt));
}
},
},
classMethods: {
isPassword: (encodedPassword, password) => bcrypt.compareSync(password, encodedPassword),
},
});


module.exports = User;
module.exports = User;
40 changes: 20 additions & 20 deletions src/api/models/users.model.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
const mongoose = require("../../config/mongodb");

const Users = mongoose.Schema({
username:{
type:String,
required:true
username: {
type: String,
required: true,
},
email:{
type:String,
required:true
email: {
type: String,
required: true,
},
password:{
type:String,
required:true
password: {
type: String,
required: true,
},
createdAt:{
type:Date,
default: Date.now()
createdAt: {
type: Date,
default: Date.now(),
},
tipo:{
type:String,
enum:['ADMIN', 'USUARIO'],
default:'USUARIO',
required:true
}
})
tipo: {
type: String,
enum: ["ADMIN", "USUARIO"],
default: "USUARIO",
required: true,
},
});

module.exports = mongoose.model('users', Users)
module.exports = mongoose.model("users", Users);
12 changes: 6 additions & 6 deletions src/api/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ const validate = require("express-validation");
const { create } = require("../controllers/user.controller");
const { registrar } = require("../validations/user.validation");
const routerUser = require("./user.routes");
const graphqlHTTP = require('express-graphql')
const { schema } = require('../models/UserSchema');
const graphqlHTTP = require("express-graphql");
const { schema } = require("../models/UserSchema");

const router = express.Router();

router.use("/users", routerUser);
router.use('/graphql', graphqlHTTP({
schema:schema,
graphiql:true
router.use("/graphql", graphqlHTTP({
schema : schema ,
graphiql : true,
}));
router.post("/cadastro", validate(registrar), create);

module.exports = router;
module.exports = router;
10 changes: 5 additions & 5 deletions src/api/routes/user.routes.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
const express = require("express");
const { listarUsuarios, loadUser, get, deleteUser, update } = require("../controllers/user.controller");
const validate = require('express-validation')
const { registrar } = require("../validations/user.validation")
const validate = require("express-validation");
const { registrar } = require("../validations/user.validation");
const router = express.Router();


router.route("/")
.get(listarUsuarios)
.get(listarUsuarios);

router
.route("/:id")
.get(loadUser)
.put(validate(registrar), update)
.delete(deleteUser)
.delete(deleteUser);

module.exports = router;
module.exports = router;
Loading

0 comments on commit df77245

Please sign in to comment.