쇼핑몰 구현 프로젝트

[쇼핑몰 구현 프로젝트] 09. 사용자 관련 기능

binning 2024. 6. 23. 16:04

① Frontend

- 유저정보 수정 시 기존 데이터를 useEffect로 넣기

  useEffect(() => {
    setFormData({
      name: userData?.name || "",
      address: userData?.address || "",
      phonenumber: userData?.phonenumber || "",
    });
  }, [userData]);

 

- Data를 불러올 때 useEffect안에 함수를 작성하여 불러오기

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const responseData = await sendRequest(
          `${process.env.REACT_APP_BACKEND_URL}/users/${userId}`
        );
        setUserData(responseData.user);
      } catch (err) {
        setIsError(true);
        setErrorMessage(err.message);
      }
    };
    fetchUser();
  }, [sendRequest, userId]);

 

② Backend

- Controller ( payment에 session 사용 - 오류 방지 )

const getUser = async (req, res, next) => {
  const userId = req.params.uid;

  let user;
  
  try {
    user = await User.findById(userId).populate('cart history');
  } catch (err) {
    const error = new Error('something went wrong');
    error.code = 500;
    return next(error);
  }

  if (!user) {
    const error = new Error('can not find user');
    error.code = 404;
    return next(error);
  }

  res.status(200).json({ user: user.toObject({ getters: true }) });
};

const editUser = async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const error = new Error('Invalid inputs');
    error.code = 422;
    return next(error);
  }
  const { name, address, phonenumber } = req.body;

  const userId = req.params.uid;

  let user;
  try {
    user = await User.findById(userId);
  } catch (err) {
    const error = new Error('something went wrong');
    error.code = 500;
    return next(error);
  }

  user.name = name;
  user.address = address;
  user.phonenumber = phonenumber;

  try {
    await user.save();
  } catch (err) {
    const error = new Error('something went wrong');
    error.code = 500;
    return next(error);
  }

  res.status(200).json({ user: user.toObject({ getters: true }) });
};

const payment = async (req, res, next) => {
  const userId = req.params.uid;

  let user;
  
  try {
    user = await User.findById(userId).populate('cart');
  } catch (err) {
    const error = new Error('something went wrong');
    error.code = 500;
    return next(error);
  }

  if (!user) {
    const error = new Error('can not find user');
    error.code = 404;
    return next(error);
  }
  
  
  try {
    const sess = await mongoose.startSession();
    sess.startTransaction();
    user.cart.map(async(product) => { 
      product.stock = product.stock-1;
      user.history.push(product);
      await product.save({session: sess});
    });
    user.cart = [];
    await user.save({session: sess});
    await sess.commitTransaction();
  } catch (err) {
    const error = new Error('something went wrong');
    error.code = 500;
    return next(error);
  }
  
  res.status(200).json({ user: user.toObject({ getters: true })});
};