소스 검색

Do not mutate original API response

Tatiana Inama 4 년 전
부모
커밋
cf74a760cc
2개의 변경된 파일31개의 추가작업 그리고 16개의 파일을 삭제
  1. 12 5
      pages/api/login.ts
  2. 19 11
      pages/api/signup.ts

+ 12 - 5
pages/api/login.ts

@@ -1,6 +1,5 @@
 import axios from "axios";
 import axios from "axios";
 import type { NextApiHandler } from "next";
 import type { NextApiHandler } from "next";
-import { errorHandler } from "../../utils/apiErrorHandler";
 
 
 const loginHandler: NextApiHandler = async (req, res) => {
 const loginHandler: NextApiHandler = async (req, res) => {
   if (req.body) {
   if (req.body) {
@@ -10,10 +9,18 @@ const loginHandler: NextApiHandler = async (req, res) => {
         req.body,
         req.body,
         { headers: { "Content-Type": "application/json" } }
         { headers: { "Content-Type": "application/json" } }
       );
       );
-      res.status(200).json(response.data);
-    } catch (error) {
-      const { status, message } = errorHandler(error);
-      res.status(status).json({ message });
+      res.status(response.status).json(response.data);
+    } catch (e) {
+      if (axios.isAxiosError(e)) {
+        res.status(e.response?.status || 500).json(e.response?.data);
+      } else {
+        res
+          .status(500)
+          .json({
+            message:
+              "There was an error processing the request, please try again.",
+          });
+      }
     }
     }
   }
   }
 };
 };

+ 19 - 11
pages/api/signup.ts

@@ -1,19 +1,27 @@
 import axios from "axios";
 import axios from "axios";
 import type { NextApiHandler } from "next";
 import type { NextApiHandler } from "next";
-import { errorHandler } from "../../utils/apiErrorHandler";
 
 
 const signUpHandler: NextApiHandler = async (req, res) => {
 const signUpHandler: NextApiHandler = async (req, res) => {
-  if (req.body) {
-    try {
-      const response = await axios.post(
-        `${process.env.PRISMA_API}/register`,
-        req.body,
-        { headers: { "Content-Type": "application/json" } }
+  try {
+    const response = await axios.post(
+      `${process.env.PRISMA_API}/register`,
+      req.body,
+      { headers: { "Content-Type": "application/json" } }
+    );
+    res.status(response.status).json(response.data);
+  } catch (e) {
+    if (axios.isAxiosError(e)) {
+      res.status(e.response?.status || 500).json(e.response?.data);
+    } else {
+      console.error(
+        `Error while trying to register: ${JSON.stringify(req.body, null, 2)}`
       );
       );
-      res.status(200).json(response.data);
-    } catch (error) {
-      const { status, message } = errorHandler(error);
-      res.status(status).json({ message });
+      res
+        .status(500)
+        .json({
+          message:
+            "There was an error processing the request, please try again.",
+        });
     }
     }
   }
   }
 };
 };