Skip to content

Commit

Permalink
Do formatting fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed May 12, 2020
1 parent f4bc51a commit d527930
Show file tree
Hide file tree
Showing 19 changed files with 68 additions and 170 deletions.
4 changes: 2 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"node": true,
"jest": true
},
"extends": ["airbnb-base", "plugin:prettier/recommended", "plugin:jest/recommended", "plugin:security/recommended"],
"plugins": ["prettier", "jest", "security"],
"extends": ["airbnb-base", "plugin:jest/recommended", "plugin:security/recommended", "plugin:prettier/recommended"],
"plugins": ["jest", "security", "prettier"],
"parserOptions": {
"ecmaVersion": 2018
},
Expand Down
6 changes: 1 addition & 5 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"printWidth": 125,
"endOfLine": "lf"
"printWidth": 125
}
26 changes: 10 additions & 16 deletions src/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,12 @@ dotenv.config({ path: path.join(__dirname, '../../.env') });

const envVarsSchema = Joi.object()
.keys({
NODE_ENV: Joi.string()
.valid('production', 'development', 'test')
.required(),
NODE_ENV: Joi.string().valid('production', 'development', 'test').required(),
PORT: Joi.number().default(3000),
MONGODB_URL: Joi.string()
.required()
.description('Mongo DB url'),
JWT_SECRET: Joi.string()
.required()
.description('JWT secret key'),
JWT_ACCESS_EXPIRATION_MINUTES: Joi.number()
.default(30)
.description('minutes after which access tokens expire'),
JWT_REFRESH_EXPIRATION_DAYS: Joi.number()
.default(30)
.description('days after which refresh tokens expire'),
MONGODB_URL: Joi.string().required().description('Mongo DB url'),
JWT_SECRET: Joi.string().required().description('JWT secret key'),
JWT_ACCESS_EXPIRATION_MINUTES: Joi.number().default(30).description('minutes after which access tokens expire'),
JWT_REFRESH_EXPIRATION_DAYS: Joi.number().default(30).description('days after which refresh tokens expire'),
SMTP_HOST: Joi.string().description('server that will send the emails'),
SMTP_PORT: Joi.number().description('port to connect to the email server'),
SMTP_USERNAME: Joi.string().description('username for email server'),
Expand All @@ -41,7 +31,11 @@ module.exports = {
port: envVars.PORT,
mongoose: {
url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
options: { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true },
options: {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
},
},
jwt: {
secret: envVars.JWT_SECRET,
Expand Down
2 changes: 1 addition & 1 deletion src/config/logger.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const winston = require('winston');
const config = require('./config');

const enumerateErrorFormat = winston.format(info => {
const enumerateErrorFormat = winston.format((info) => {
if (info instanceof Error) {
Object.assign(info, { message: info.stack });
}
Expand Down
4 changes: 2 additions & 2 deletions src/config/morgan.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ const errorResponseFormat = `${getIpFormat()}:method :url :status - :response-ti

const successHandler = morgan(successResponseFormat, {
skip: (req, res) => res.statusCode >= 400,
stream: { write: message => logger.info(message.trim()) },
stream: { write: (message) => logger.info(message.trim()) },
});

const errorHandler = morgan(errorResponseFormat, {
skip: (req, res) => res.statusCode < 400,
stream: { write: message => logger.error(message.trim()) },
stream: { write: (message) => logger.error(message.trim()) },
});

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const getUsers = catchAsync(async (req, res) => {
const filter = pick(req.query, ['name', 'role']);
const options = getQueryOptions(req.query);
const users = await User.find(filter, null, options);
const response = users.map(user => user.transform());
const response = users.map((user) => user.transform());
res.send(response);
});

Expand Down
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const exitHandler = () => {
}
};

const unexpectedErrorHandler = error => {
const unexpectedErrorHandler = (error) => {
logger.error(error);
exitHandler();
};
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const verifyCallback = (req, resolve, reject, requiredRights) => async (err, use

if (requiredRights.length) {
const userRights = roleRights.get(user.role);
const hasRequiredRights = requiredRights.every(requiredRight => userRights.includes(requiredRight));
const hasRequiredRights = requiredRights.every((requiredRight) => userRights.includes(requiredRight));
if (!hasRequiredRights && req.params.userId !== user.id) {
return reject(new ApiError(httpStatus.FORBIDDEN, 'Forbidden'));
}
Expand All @@ -25,7 +25,7 @@ const auth = (...requiredRights) => async (req, res, next) => {
passport.authenticate('jwt', { session: false }, verifyCallback(req, resolve, reject, requiredRights))(req, res, next);
})
.then(() => next())
.catch(err => next(err));
.catch((err) => next(err));
};

module.exports = auth;
4 changes: 2 additions & 2 deletions src/middlewares/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ const httpStatus = require('http-status');
const { pick } = require('lodash');
const ApiError = require('../utils/ApiError');

const validate = schema => (req, res, next) => {
const validate = (schema) => (req, res, next) => {
const validSchema = pick(schema, ['params', 'query', 'body']);
const object = pick(req, Object.keys(validSchema));
const { value, error } = Joi.compile(validSchema)
.prefs({ errors: { label: 'key' } })
.validate(object);

if (error) {
const errorMessage = error.details.map(details => details.message).join(', ');
const errorMessage = error.details.map((details) => details.message).join(', ');
return next(new ApiError(httpStatus.BAD_REQUEST, errorMessage));
}
Object.assign(req, value);
Expand Down
10 changes: 5 additions & 5 deletions src/models/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,27 +47,27 @@ const userSchema = mongoose.Schema(
}
);

userSchema.statics.isEmailTaken = async function(email, excludeUserId) {
userSchema.statics.isEmailTaken = async function (email, excludeUserId) {
const user = await this.findOne({ email, _id: { $ne: excludeUserId } });
return !!user;
};

userSchema.methods.isPasswordMatch = async function(password) {
userSchema.methods.isPasswordMatch = async function (password) {
const user = this;
return bcrypt.compare(password, user.password);
};

userSchema.methods.toJSON = function() {
userSchema.methods.toJSON = function () {
const user = this;
return omit(user.toObject(), ['password']);
};

userSchema.methods.transform = function() {
userSchema.methods.transform = function () {
const user = this;
return pick(user.toJSON(), ['id', 'email', 'name', 'role']);
};

userSchema.pre('save', async function(next) {
userSchema.pre('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8);
Expand Down
4 changes: 2 additions & 2 deletions src/services/token.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const verifyToken = async (token, type) => {
return tokenDoc;
};

const generateAuthTokens = async userId => {
const generateAuthTokens = async (userId) => {
const accessTokenExpires = moment().add(config.jwt.accessExpirationMinutes, 'minutes');
const accessToken = generateToken(userId, accessTokenExpires);

Expand All @@ -52,7 +52,7 @@ const generateAuthTokens = async userId => {
};
};

const generateResetPasswordToken = async userId => {
const generateResetPasswordToken = async (userId) => {
const expires = moment().add(config.jwt.resetPasswordExpirationMinutes, 'minutes');
const resetPasswordToken = generateToken(userId, expires);
await saveToken(resetPasswordToken, userId, expires, 'resetPassword');
Expand Down
4 changes: 2 additions & 2 deletions src/utils/catchAsync.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const catchAsync = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(err => next(err));
const catchAsync = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch((err) => next(err));
};

module.exports = catchAsync;
2 changes: 1 addition & 1 deletion src/utils/query.utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const getQueryOptions = query => {
const getQueryOptions = (query) => {
const page = query.page * 1 || 1;
const limit = query.limit * 1 || 100;
const skip = (page - 1) * limit;
Expand Down
16 changes: 4 additions & 12 deletions src/validations/auth.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,8 @@ const { password } = require('./custom.validation');

const register = {
body: Joi.object().keys({
email: Joi.string()
.required()
.email(),
password: Joi.string()
.required()
.custom(password),
email: Joi.string().required().email(),
password: Joi.string().required().custom(password),
name: Joi.string().required(),
}),
};
Expand All @@ -28,9 +24,7 @@ const refreshTokens = {

const forgotPassword = {
body: Joi.object().keys({
email: Joi.string()
.email()
.required(),
email: Joi.string().email().required(),
}),
};

Expand All @@ -39,9 +33,7 @@ const resetPassword = {
token: Joi.string().required(),
}),
body: Joi.object().keys({
password: Joi.string()
.required()
.custom(password),
password: Joi.string().required().custom(password),
}),
};

Expand Down
12 changes: 3 additions & 9 deletions src/validations/user.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,10 @@ const { password, objectId } = require('./custom.validation');

const createUser = {
body: Joi.object().keys({
email: Joi.string()
.required()
.email(),
password: Joi.string()
.required()
.custom(password),
email: Joi.string().required().email(),
password: Joi.string().required().custom(password),
name: Joi.string().required(),
role: Joi.string()
.required()
.valid('user', 'admin'),
role: Joi.string().required().valid('user', 'admin'),
}),
};

Expand Down
4 changes: 2 additions & 2 deletions tests/fixtures/user.fixture.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ const admin = {
role: 'admin',
};

const insertUsers = async users => {
await User.insertMany(users.map(user => ({ ...user, password: hashedPassword })));
const insertUsers = async (users) => {
await User.insertMany(users.map((user) => ({ ...user, password: hashedPassword })));
};

module.exports = {
Expand Down
Loading

0 comments on commit d527930

Please sign in to comment.