Skip to content

Instantly share code, notes, and snippets.

@artemis15
Last active September 16, 2019 18:19
Show Gist options
  • Save artemis15/75d8cb2872fed4d2c6d230e3a2699c57 to your computer and use it in GitHub Desktop.
Save artemis15/75d8cb2872fed4d2c6d230e3a2699c57 to your computer and use it in GitHub Desktop.
Business logic of User API
const express = require("express");
const userModel = require("../../models/user");
/*List of Functions
1) getUsers
2) createUser
*/
const getUsers = async (req, res, next) => {
try {
let users = await userModel.find({});
if (users.length > 0) {
return res.status(200).json({
'message': 'Data loaded successfully',
'data': users
});
}
return res.status(404).json({
'code': 'Bad_Request',
'description': 'No Data Found'
});
} catch (error) {
return res.status(500).json({
'code': 'Internal_Server_Error',
'description': 'Some Internal Server Error. Please Try Again.'
});
}
};
const createUser = async (req, res, next) => {
try {
const {
name,
email
} = req.body;
if (name === undefined || name === '') {
return res.status(422).json({
'code': 'REQUIRED_FIELD_MISSING',
'description': 'name is required',
'field': 'name'
});
}
if (email === undefined || email === '') {
return res.status(422).json({
'code': 'REQUIRED_FIELD_MISSING',
'description': 'email is required',
'field': 'email'
});
}
let isEmailExists = await userModel.findOne({
"email": email
});
if (isEmailExists) {
return res.status(409).json({
'code': 'ENTITY_ALREAY_EXISTS',
'description': 'email already exists',
'field': 'email'
});
}
const temp = {
name: name,
email: email
}
let newUser = await userModel.create(temp);
if (newUser) {
return res.status(201).json({
'message': 'user created successfully',
'data': newUser
});
} else {
throw new Error('something went worng');
}
} catch (error) {
return res.status(500).json({
'code': 'SERVER_ERROR',
'description': 'something went wrong, Please try again'
});
}
};
module.exports = {
getUsers: getUsers,
createUser: createUser
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment