Skip to content

Instantly share code, notes, and snippets.

@Cool-sami12
Last active July 1, 2020 14:16
Show Gist options
  • Select an option

  • Save Cool-sami12/f196409a656df083a79593ac1aabf180 to your computer and use it in GitHub Desktop.

Select an option

Save Cool-sami12/f196409a656df083a79593ac1aabf180 to your computer and use it in GitHub Desktop.
const makeValidation = require('@withvoid/make-validation');
const UserModel = require('../models/user.js');
const {USER_TYPES} = UserModel;
module.exports = {
onGetAllUsers: async (req, res) => {
try {
const users = await UserModel.getUsers();
return res.status(200).json({ success: true, users });
} catch (error) {
return res.status(500).json({ success: false, error: error })
}
},
onGetUserById: async (req, res) => {
try {
const user = await UserModel.getUserById(req.params.id);
return res.status(200).json({ success: true, user });
} catch (error) {
return res.status(500).json({ success: false, error: error })
}
},
onCreateUser: async (req, res) => {
try {
const validation = makeValidation(types =>({
payload: req.body,
checks: {
firstName: { type: types.string },
lastName: { type: types.string },
type: { type: types.enum,
options: { enum: USER_TYPES } },
}
}));
if (!validation.success) return res.status(400).json(validation);
const { firstName, lastName, type } = req.body;
const user = await UserModel.createUser(firstName, lastName, type);
console.log('test3');
return res.status(200).json({ success: true, user });
} catch (error) {
console.log(error);
return res.status(500).json({ success: false, error: error })
}
},
onDeleteUserById: async (req, res) => {
try {
const user = await UserModel.deleteByUserById(req.params.id);
return res.status(200).json({
success: true,
message: `Deleted a count of ${user.deletedCount} user.`
});
} catch (error) {
return res.status(500).json({ success: false, error: error })
}
},
};
Mongo has connected successfully
POST /users 500 524.686 ms - 28
[nodemon] restarting due to changes...
[nodemon] starting `node server/index.js`
Listening on port :: http:/localhost:3000/
Mongo has connected successfully
TypeError: UserModel.createUser is not a function
at onCreateUser (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\controllers\user.js:37:36)
at Layer.handle [as handle_request] (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:317:13)
at C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\express\lib\router\index.js:275:10)
at urlencodedParser (C:\Users\SAMUEL\Documents\codes\chatapp\chatapp\node_modules\body-parser\lib\types\urlencoded.js:82:7)
POST /users 500 334.781 ms - 28
const config = {
db:{
url: 'localhost:27017',
name: 'chatdb'
}
}
export default config
/// i am having a bug with line 8
/* export default config
^^^^^^
SyntaxError: Unexpected token export */
const mongoose = require('mongoose');
const { v4 : uuidv4} = require('uuid');
const USER_TYPES = {
CONSUMER: "consumer",
SUPPORT: "support"
};
const userSchema = new mongoose.Schema(
{
_id:{
type: String ,
default: () => uuidv4().replace(/\-/g, ""),
},
firstName: String,
lastName: String,
type:String,
},
{
timestamps:true,
collection: "users",
}
);
userSchema.statics.createUser = async function (firstName,lastName,type) {
return this.create({ firstName, lastName, type });
}
userSchema.statics.getUserById = async function (id) {
try {
const user = await this.findOne({ _id: id });
if (!user) throw ({ error: 'No user with this id found' });
return user;
} catch (error) {
throw error;
}
}
userSchema.statics.getUsers = async function () {
try {
const users = await this.find();
return users;
} catch (error) {
throw error;
}
}
userSchema.statics.deleteByUserById = async function (id) {
try {
const result = await this.remove({ _id: id });
return result;
} catch (error) {
throw error;
}
}
const usermodel = mongoose.model("User", userSchema);
module.exports = {
usermodel,
USER_TYPES
}
const mongoose = require('mongoose');
const config = require('../config/index.js');
const CONNECTION_URL = `mongodb://${config.db.url}/${config.db.name}`
mongoose.connect(CONNECTION_URL, {
useNewUrlParser:true,
useUnifiedTopology: true
})
mongoose.connection.on('connected', () => {
console.log ('Mongo has connected successfully');
})
mongoose.connection.on('reconnected', () => {
console.log('Mongo has reconnected')
})
mongoose.connection.on('error', error => {
console.log('Mongo connection has an error', error)
mongoose.disconnect()
})
mongoose.connection.on('disconnected', () => {
console.log('Mongo connection is disconnected')
})
const express = require('express');
const router = express.Router();
//controllers
const user = require('../controllers/user.js');
router
.get('/', user.onGetAllUsers)
.post('/', user.onCreateUser)
.get('/:id', user.onGetUserById)
.delete('/:id', user.onDeleteUserById)
module.exports = router;
const express = require('express');
const users = require('../controlllers/user.js');
const { encode } = require('../middlewares/jwt.js');
const router = express.Router();
router
.post('/login/:userId', encode, (req, res, next) => { });
module.exports = router;
@stephengfriend
Copy link

The syntax you're using on line 8 only works when using ES Modules or a transpiler such as Babel with the import plugin. There are a couple of ways to solve this. The easiest is to just use module.exports. module isn't global, but local to the module where it's being defined.

module.exports = config on line 8 should solve your issue.

For more information on the nuance between them, this is a terse but solid reference: https://adrianmejia.com/getting-started-with-node-js-modules-require-exports-imports-npm-and-beyond/

@Cool-sami12
Copy link
Author

Okay thanks for link i will check it out ......i have updated the files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment