Skip to content

Commit 872b941

Browse files
Refactor: ESLINT
1 parent fe042a5 commit 872b941

File tree

9 files changed

+1434
-204
lines changed

9 files changed

+1434
-204
lines changed

newrelic_agent.log

Lines changed: 1227 additions & 0 deletions
Large diffs are not rendered by default.

server.js

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
1-
require('newrelic');
2-
import restify from 'restify'
3-
import cluster from 'cluster'
4-
import { graphqlRestify, graphiqlRestify } from 'apollo-server-restify'
5-
require('./src/config/database')
1+
import restify from 'restify';
2+
import cluster from 'cluster';
3+
import { graphqlRestify } from 'apollo-server-restify';
4+
import Authentication from './src/controllers/auth';
5+
import Registration from './src/controllers/registration';
66

7-
import Authentication from './src/controllers/auth'
8-
import Registration from './src/controllers/registration'
7+
require('./src/config/database');
8+
require('newrelic');
9+
const CPUS = require('os').cpus().length;
910

10-
const PORT = (process.env.PORT || 8888)
11-
const CPUS = require('os').cpus().length
12-
const CPU_BY_WORKER = 2
13-
const WORKERS = (CPUS / CPU_BY_WORKER)
11+
const PORT = (process.env.PORT || 8888);
12+
const CPU_BY_WORKER = 2;
13+
const WORKERS = (CPUS / CPU_BY_WORKER);
1414

1515
if (cluster.isMaster) {
16-
console.info(`Master server is active: Forking ${WORKERS} workers with ${CPU_BY_WORKER} cpu by worker.`)
16+
console.log(`Server is active, forking ${WORKERS} workers with ${CPU_BY_WORKER} cpu by worker`);
1717

18-
for (let i = 0; i < WORKERS; i++){
19-
cluster.fork()
18+
for (let i = 0; i < WORKERS; i += 1) {
19+
cluster.fork();
2020
}
2121
cluster.on('exit', (worker) => {
22-
console.error(`Worker ${worker.id} has died! Creating a new one.`)
23-
cluster.fork()
24-
})
22+
console.error(`Worker ${worker.id} has died! Creating a new one.`);
23+
cluster.fork();
24+
});
2525
} else {
26-
const server = restify.createServer({'Node Server': 'v1.0.0'})
26+
const server = restify.createServer({ 'Node Server': 'v1.0.0' });
2727

28-
server.use(restify.plugins.bodyParser())
29-
server.use(restify.plugins.queryParser())
28+
server.use(restify.plugins.bodyParser());
29+
server.use(restify.plugins.queryParser());
3030

31-
server.post('/login', Authentication.login)
32-
server.post('/registration', Registration.register)
33-
server.get('/graphql', graphqlRestify((req, res) => Authentication.verifyToken(req, res)))
34-
server.post('/graphql', graphqlRestify((req, res) => Authentication.verifyToken(req, res)))
31+
server.post('/login', Authentication.login);
32+
server.post('/registration', Registration.register);
33+
server.get('/graphql', graphqlRestify((req, res) => Authentication.verifyToken(req, res)));
34+
server.post('/graphql', graphqlRestify((req, res) => Authentication.verifyToken(req, res)));
3535

3636
server.listen(PORT, () => {
37-
console.info(`Worker ${cluster.worker.id} spawned for port ${PORT}.`)
38-
})
37+
console.info(`Worker ${cluster.worker.id} spawned in ${PORT}`);
38+
});
3939
}

src/config/database.js

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,59 +3,63 @@
33
*
44
* Português / English
55
*
6-
* Host: Heroku mLab
7-
* Database Type: MongoDB
8-
* Database Name: heroku_clzfdlwj
9-
* User: serventec
10-
* Password: portalserventec
6+
* Host: Heroku mLab
7+
* Database Type: MongoDB
8+
* Database Name: heroku_clzfdlwj
9+
* User: serventec
10+
* Password: portalserventec
1111
*
12-
* PT: Configuração de base de dados local
12+
* PT: Configuração de base de dados local
1313
* EN: Configuration of local database
14-
* mongoose.connect('mongodb://localhost/databaseName');
14+
* mongoose.connect('mongodb://localhost/databaseName');
1515
*
1616
*/
17-
let mongoose = require('mongoose');
17+
const mongoose = require('mongoose');
1818

19-
// mongoose.connect('mongodb://herokumlab:[email protected]:45287/heroku_k34fbvx8', { useMongoClient: true, config: {autoIndex: false} });
20-
// mongoose.connect('mongodb://localhost/graphql', { useMongoClient: true });
21-
mongoose.connect('mongodb://live:[email protected]:45312/heroku_jwprwsr5', { useMongoClient: true });
22-
mongoose.Promise = global.Promise;
19+
// mongoose.connect('mongodb://herokumlab:[email protected]:45287/heroku_k34fbvx8', { useMongoClient: true, config: {autoIndex: false} });
20+
// mongoose.connect('mongodb://localhost/graphql', { useMongoClient: true });
21+
mongoose.connect('mongodb://live:[email protected]:45312/heroku_jwprwsr5', { useMongoClient: true });
22+
mongoose.Promise = global.Promise;
2323

2424

2525
/**
2626
* PT: Função para imprimir no console se a conxão com o banco foi efetuada
2727
* EN: Function to print in console if the database connection was a success
2828
*/
2929

30-
mongoose.connection.on('connected', function(){
31-
console.log('Conectado ao Banco MongoDB');
32-
});
30+
mongoose.connection.on('connected', () => {
31+
console.log('Conectado ao Banco MongoDB');
32+
});
3333

3434
/**
3535
* PT: Evitando derrubar aplicação caso não tenha conexão
3636
* EN: Avoiding close the application if not get the connection
3737
*/
3838

39-
mongoose.connection.on('error', function(error){
40-
console.log('Erro na conexão: ' + error);
41-
});
39+
mongoose.connection.on('error', (error) => {
40+
console.log(`Erro na conexão: ${error}`);
41+
});
4242

4343
/**
4444
* EN: Evitando derrubar a app Caso perda de conexão
4545
* PT: Avoiding close the application if lost connection
4646
*/
4747

48-
mongoose.connection.on('disconnected', function(){
49-
console.log('Desconectado do banco MongoDB');
50-
});
48+
mongoose.connection.on('disconnected', () => {
49+
console.log('Desconectado do banco MongoDB');
50+
});
5151

52-
/** PT: Process pode ser usado em qualquer lugar de nossa aplicação com o process podemos acessar as informações e eventos de nossa app, este caso estamos acessando o process para saber se a app foi finalizada e assim garantir a finalização da conexão com banco.
53-
* EN: Accessing the process to ensure close the database connection when the application finish
52+
/**
53+
* PT: Process pode ser usado em qualquer lugar de nossa aplicação com o process podemos
54+
* acessar as informações e eventos de nossa app, este caso estamos acessando o process
55+
* para saber se a app foi finalizada e assim garantir a finalização da conexão com banco.
56+
*
57+
* EN: Accessing the process to ensure close the database connection when the application finish
5458
*/
5559

56-
process.on('SIGINT', function(){
57-
mongoose.connection.close(function(){
58-
console.log('conexão fechada pelo temino da aplicação');
59-
process.exit(0);
60-
});
61-
});
60+
process.on('SIGINT', () => {
61+
mongoose.connection.close(() => {
62+
console.log('conexão fechada pelo temino da aplicação');
63+
process.exit(0);
64+
});
65+
});

src/controllers/auth.js

Lines changed: 61 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,73 @@
1-
import mongoose from 'mongoose'
2-
import { makeExecutableSchema } from 'graphql-tools'
3-
import jwt from 'jsonwebtoken'
4-
import bcrypt from 'bcrypt'
1+
import { makeExecutableSchema } from 'graphql-tools';
2+
import jwt from 'jsonwebtoken';
3+
import bcrypt from 'bcrypt';
54

6-
import typeDefs from '../graphql/typeDefs'
7-
import resolvers from '../graphql/resolvers'
8-
import context from '../graphql/context'
9-
import model from '../graphql/user_schema/user.model'
5+
import typeDefs from '../graphql/typeDefs';
6+
import resolvers from '../graphql/resolvers';
7+
import context from '../graphql/context';
8+
import model from '../graphql/user_schema/user.model';
109

11-
const userModel = model.User
12-
const fakeContext= mongoose.model('Fake', mongoose.Schema({}))
10+
const userModel = model.User;
1311

14-
const saltRounds = 15
15-
let authController = {}
16-
const SECRET = 'secret'
12+
const authController = {};
13+
const SECRET = 'secret';
1714

18-
authController.login = (req, res) => {
19-
userModel.findOne({ email: req.body.email })
20-
.then(
21-
(user) => {
22-
bcrypt.compare(req.body.password, user.password, (error, success) => {
23-
if (error) {
24-
res.send(401, { error: error, message: 'Password mismatch'})
25-
} else if (success) {
26-
const token = jwt.sign({ user_id: user._id }, SECRET, { expiresIn: '3h' })
27-
return res.send(
28-
200,
29-
{
30-
_id: user._id,
31-
nickname : user.nickname,
32-
username: user.username,
33-
photo : user.photo,
34-
email : user.email,
35-
token: token,
36-
}
37-
)
38-
}
39-
})
40-
}
41-
)
42-
.catch(error => res.send(401, { error: error, message: 'Error, user does not exists' }))
43-
}
44-
45-
const generateSecureSchema = () => {
46-
const schema = makeExecutableSchema({
47-
typeDefs,
48-
resolvers,
15+
authController.login = (req, res) => {
16+
userModel.find({ email: req.body.email })
17+
.then((user) => {
18+
bcrypt.compare(req.body.password, user.password, (error, success) => {
19+
if (error) {
20+
res.send(401, { error, message: 'Password mismatch' });
21+
} else if (success) {
22+
const token = jwt.sign({ user_id: user._id }, SECRET, { expiresIn: '3h' });
23+
return res.send(
24+
200,
25+
{
26+
_id: user._id,
27+
nickname: user.nickname,
28+
username: user.username,
29+
photo: user.photo,
30+
email: user.email,
31+
token,
32+
},
33+
);
34+
}
35+
});
4936
})
37+
.catch(error => res.send(401, { error, message: 'Error, user does not exists' }));
38+
};
5039

51-
let generated = {schema, context}
52-
53-
return generated
54-
}
40+
const generateSecureSchema = () => {
41+
const schema = makeExecutableSchema({
42+
typeDefs,
43+
resolvers,
44+
});
5545

56-
authController.verifyToken = (req, res) => {
57-
const TOKEN = req.header('Authorization')
58-
let secureSchema
46+
const generated = { schema, context };
5947

60-
if (TOKEN)
61-
jwt.verify(TOKEN, SECRET,
62-
(error, decoded) => {
63-
if (error)
64-
res.send(401, {message: 'Error: invalid token'})
65-
else
66-
secureSchema = generateSecureSchema()
67-
}
68-
)
48+
return generated;
49+
};
6950

70-
else
71-
res.send(401, {message: 'Error: token is required'})
51+
authController.verifyToken = (req, res) => {
52+
const TOKEN = req.header('Authorization');
53+
let secureSchema;
7254

73-
return secureSchema
55+
if (TOKEN) {
56+
jwt.verify(
57+
TOKEN, SECRET,
58+
(error, decoded) => {
59+
if (error) {
60+
res.send(401, { message: 'Error: invalid token' });
61+
} else if (decoded) {
62+
secureSchema = generateSecureSchema();
63+
}
64+
},
65+
);
66+
} else {
67+
res.send(401, { message: 'Error: token is required' });
7468
}
7569

76-
export default authController
70+
return secureSchema;
71+
};
72+
73+
export default authController;

src/controllers/registration.js

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
1-
const mongoose = require('mongoose');
2-
const bcrypt = require('bcrypt');
3-
const saltRounds = 15;
4-
const jwt = require('jsonwebtoken');
5-
const model = require('../graphql/user_schema/user.model').User
1+
import bcrypt from 'bcrypt';
62

7-
let registrationController = {};
8-
const SECRET = 'secret';
3+
const model = require('../graphql/user_schema/user.model').User;
94

10-
registrationController.register = (req, res) => {
11-
bcrypt.hash(req.body.password, saltRounds, (err, hash) => {
12-
req.body.password = hash;
13-
model.create(req.body).then(
14-
user => res.send(200, {user: user}))
15-
.catch(error => res.send(404, {error: error}))
16-
})
17-
};
5+
const SALT_ROUNDS = 2;
6+
const registrationController = {};
7+
8+
registrationController.register = (req, res) => {
9+
bcrypt.hash(req.body.password, SALT_ROUNDS, (err, hash) => {
10+
req.body.password = hash;
11+
model.create(req.body).then(user => res.send(200, { user }))
12+
.catch(error => res.send(404, { error }));
13+
});
14+
};
1815

1916
export default registrationController;
Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1-
import mongoose from 'mongoose'
1+
import mongoose from 'mongoose';
22

3-
const schema = mongoose.Schema({
4-
name: {
5-
type: String,
6-
required: false,
7-
},
8-
description : {
9-
type: String,
10-
required: false,
11-
},
12-
}, {timestamps: true})
3+
const schema = mongoose.Schema(
4+
{
5+
name: {
6+
type: String,
7+
required: false,
8+
},
9+
description: {
10+
type: String,
11+
required: false,
12+
},
13+
},
14+
{
15+
timestamps: true,
16+
},
17+
);
1318

14-
exports.Post = mongoose.model('Post', schema)
19+
exports.Post = mongoose.model('Post', schema);
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
export default {
22
Query: {
33
allPosts: async (parent, args, { Post }) => {
4-
const posts = await Post.find()
5-
return posts.map(post => {
6-
post._id = post._id.toString()
7-
return post
8-
})
4+
const posts = await Post.find();
5+
return posts.map((post) => {
6+
post._id = post._id.toString();
7+
return post;
8+
});
99
},
1010
findPost: async (parent, args, { Post }) => {
11-
let post = await post.findOne({ '_id': args })
12-
post._id = post._id.toString()
13-
return post
14-
}
11+
const post = await post.findOne({ _id: args });
12+
post._id = post._id.toString();
13+
return post;
14+
},
1515
},
1616
Mutation: {
1717
createPost: async (parent, args, { Post }) => {
18-
const post = await new Post(args).save()
19-
post._id = post._id.toString()
20-
return post
21-
}
22-
}
23-
}
18+
const post = await new Post(args).save();
19+
post._id = post._id.toString();
20+
return post;
21+
},
22+
},
23+
};

0 commit comments

Comments
 (0)