0

It's my first time building user auth using railway MySQL database and when I make a POST request in Postman, it returns 500 Internal Server Error.

I write the code in 3 files: userRepository.js, userService.js and userController.js.

Here is userRepository.js:

  const User = require('../models');
  const createUser = async (data) => {
    return User.create(data)
  };

  const getUserByUsername = async (username) => {
    return User.findOne({
      where: {
       username: username,
      },
    });
  };
  
  const getUserByEmail = async (email) => {
    return User.findOne({
      where: {
        email: email,
      },
     });
  };
  
  module.exports = {
    createUser,
    getUserByUsername,
    getUserByEmail,
  };

Here is userService.js

const userRepository = require('../repositories/userRepository');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const registerUser = async (data) => {
  const { username, email, password } = data;
  
  const existingUserByUsername = await userRepository.getUserByUsername(username);
  if (existingUserByUsername) {
    throw new Error('Username already exists');
  }

  const existingUserByEmail = await userRepository.getUserByEmail(email);
  if (existingUserByEmail) {
    throw new Error('Email already exists');
  }

  const hashedPassword = await bcrypt.hash(password, 10);
  const user = await userRepository.createUser({
    username,
    email,
    password: hashedPassword
  });

  return user;
};

const loginUser = async (data) => {
  const { username, password } = data;

  const user = await userRepository.getUserByUsername(username);
  if (!user) {
    throw new Error('User not found');
  }

  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    throw new Error('Invalid password');
  }

  const token = jwt.sign({ userId: user.id }, 'JWT_SECRET');
  return token;
};

module.exports = {
  registerUser,
  loginUser
};

And here is userController.js:

const userService = require('../services/userService');

const register = async (req, res, next) => {
  try {
    const user = await userService.registerUser(req.body);
    return res.status(201).json({
      status: 'success',
      message: 'User created successfully',
      data: user
    });
  } catch (err) {
    if (
      err.message === 'Username already exists' ||
      err.message === 'Email already exists'
    ) {
      return res.status(409).json({ 
        status: 'error',
        error: err.message
      });
    } else {
      return res.status(500).json({ 
        status: 'error',
        message: 'Internal Server Error',
        data: err
      });
    }
    next(err);
  }
};

const login = async (req, res, next) => {
  try {
    const token = await userService.loginUser(req.body);
    return res.json({ 
      status: 'success',
      message: 'User logged in successfully',
      data: token
    });
  } catch (err) {
    if (
      err.message === 'User not found' ||
      err.message === 'Invalid password' 
    ) {
      return res.status(401).json({ 
        status: 'error',
        error: err.message
      });
    } else {
      return res.status(500).json({ 
        status: 'error',
        message: 'Internal Server Error',
        data: err
      });
    }
    next(err);
  }
};

module.exports = {
  register,
  login
};

Any help would be appreciated. Thank you.

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
fay
  • 21
  • 3
  • If it's your error being popped, you do pass back `data`. Anything useful in there? – tadman May 09 '23 at 22:10
  • i think it is being called when i try to send POST request on postman, because when i start to run this code in vscode, this code is running as it should. but i don't really sure either @tadman – fay May 09 '23 at 22:18
  • Your server or Express itself might pop a 500 if it encounters some kind of fault while processing, so it's worth seeing if this is your exception or some other one before going deeper. You could even change your 500 to a 503 and see if you get 503 all of a sudden. – tadman May 09 '23 at 22:30
  • Postman is not involved in any way into this question. The error is returned by the server and I bet it returns the same response when the request is issued with `curl` or other HTTP client. – axiac May 09 '23 at 22:31
  • i found a new error, it throws `User.findOne is not a function`, how could this happen? it is already exist in each file @tadman – fay May 09 '23 at 22:49
  • Is `User` a Sequelize model? – tadman May 09 '23 at 23:46
  • there are some ambiguous between user and User and i just swap it. and there's a thing, it returns new error `Cannot read properties of undefined (reading 'findOne')`. anyways, user is a sequelize model @tadman – fay May 10 '23 at 00:18
  • `const User = require('../models');` is probably incorrect. It might be `const { User } = require(...)` as you need to destructure. – tadman May 10 '23 at 00:30
  • i just change it and it throws a new again again `string violation: username cannot be an array or an object` and here is what i want to put in database ``` { "username": "jane doe", "email": "janedoe@gmail.com", "password": "janedoe", "role": "customer" } ``` and datatype of username is string @tadman – fay May 10 '23 at 00:52
  • You should have a look at `req.body` and see what's in there. Maybe you're missing something in how it's structured. – tadman May 10 '23 at 14:32
  • it's solved and you're right, there's something wrong in req.body. thank you – fay May 10 '23 at 14:57

0 Answers0