medusajs / medusa

The world's most flexible commerce platform.
https://medusajs.com
MIT License
25.93k stars 2.6k forks source link

Custom API endpoints works only when server restarted #4061

Closed adevinwild closed 11 months ago

adevinwild commented 1 year ago

Bug report

Describe the bug

When using a custom endpoint I have an error until I restart the backend server.

First API call 404 NOT FOUND

Second API call (AFTER A SAVE ON FILE with medusa develop) 200 SUCCESS

System information

Medusa version (including plugins): 1.8.x Node.js version: v18.12.1 Database:Postgres Operating system:MacOS Ventura 13 Browser (if relevant): Arc

Steps to reproduce the behavior

  1. Create a custom route inside src/api/
  2. Send a query to it
  3. Save the file
  4. Send a query again

Expected behavior

it should detect the router directly on launch

Additional context

i have migrated from 1.7.x to 1.8.x

olivermrbl commented 1 year ago

This behavior seems correct to me. Saving the file triggers hot reloading i.e. builds the file.

adevinwild commented 1 year ago

This behavior seems correct to me. Saving the file triggers hot reloading i.e. builds the file.

I agree with you, but my routes are already here and it should give a response when I launch the server and make a query to it... not when I reload, this issue also come when I build and start the project for production...

SaadBazaz commented 1 year ago

I'm getting a similar issue. It's been days. I get 404 on a custom route.

Route: /store/customers/is-b2b

The error:

Cannot GET /store/customers/is-b2b

This is my custom route code, in src/api/store/customers/index.js:

import * as cors from "cors"
import { Router } from "express"
import * as bodyParser from "body-parser"
import customRouteHandler from "./is-b2b-handler"
import { wrapHandler } from "@medusajs/medusa";

const customersRouter = Router()
export function getcustomersRouter(storeCorsOptions): Router {
  customersRouter.use(cors(storeCorsOptions), bodyParser.json())

  customersRouter.get(
    "/store/customers/is-b2b",
    wrapHandler(customRouteHandler)
  )

  return customersRouter
}

The customRouteHandler from "./is-b2b-handler":

import { CustomerService } from '@medusajs/medusa';
import { Request, Response } from 'express'

export default async (req: Request, res: Response): Promise<void> => {
    console.log("I'm here");

    console.log("req", req);
    console.log("req.user", req.user);

    if (!req.user) {
      res.json({
        is_b2b: false
      }).sendStatus(200);
    }

    console.log("Now I'm here");

    const customerService: CustomerService = req.scope.resolve('customerService');

    const customer = await customerService
      .retrieve(req.user.customer_id, {
        relations: ['groups']
      })

    const is_b2b = customer.groups.some((group) => group.metadata.is_b2b === "true");

    res.json({
      is_b2b
    }).sendStatus(200);
}
DhifMlak commented 1 year ago

I have the same issues with wishlist and product reviews apis !

DhifMlak commented 1 year ago

Migrating to 1.10 somehow fixed my issue !

chemicalkosek commented 1 year ago

@SaadBazaz your issue is importing cors like this:

import * as cors from "cors"

Whether it should be: import cors from 'cors'

adevinwild commented 1 year ago

I tried too but did not make it. Hi everyone, I'm back with a solution that helped me but just to answer @chemicalkosek For me, no difference in the way I imported it, but what worked was the order in which I called my CORS rules (very strange ?) By changing the order and putting my REGEX last, no more problems

adevinwild commented 1 year ago

oops wrong button

chemicalkosek commented 1 year ago

@adevinwild I was targeting my response to @SaadBazaz based on his code

adrien2p commented 1 year ago

https://github.com/medusajs/medusa/issues/4197#issuecomment-1589060663

olivermrbl commented 11 months ago

Hi there. We highly appreciate you filing an issue and showing an interest in improving Medusa.

I apologize for the delayed response.

Moving forward, we aim to do better. But we would like to start fresh. Therefore, we are considering all older issues as stale and closing them, even though they might still be relevant.

Please don’t hesitate to re-open the issue (or create a new one) if you still need a resolution or an answer.

Thanks ❤️

renanrambul commented 2 weeks ago

I'm having the same issue but I'm using API routes, the custom routes only works after rebuilding the project

backend/src/api/store/budget/route.ts

import type { MedusaRequest, MedusaResponse } from "@medusajs/medusa";
import axios from "axios";

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  try {
    const budgetService = req.scope.resolve("budgetService");
    const budgets = await budgetService.getAllBudgets();
    res.status(200).json({ budgets });
  } catch (error: any) {
    res.status(500).json({ message: error.message });
  }
}

export async function POST(req: MedusaRequest, res: MedusaResponse) {
  try {
    const budgetService = req.scope.resolve("budgetService");

    const budget = await budgetService.createBudget(req.body);

    const reportsApiUrl = process.env.REPORTS_API_URL;

    const response = await axios.post(
      reportsApiUrl + "/generate-pdf-email",
      budget,
      {
        responseType: "arraybuffer",
      }
    );
res.setHeader("Content-Type", "application/pdf");

res.setHeader(
  "Content-Disposition",
  'attachment; filename="Proposta_Comercial_ByMyCell.pdf"'
);

res.setHeader("Content-Length", response.data.length.toString());

res.send(response.data);`
 } catch (error: any) {
    res.status(400).json({ message: error.message });
  }
}

export async function PUT(req: MedusaRequest, res: MedusaResponse) {
  try {
    const { id } = req.params;
    const budgetService = req.scope.resolve("budgetService");
    const updatedBudget = await budgetService.updateBudget(id, req.body);
    res.status(200).json({ budget: updatedBudget });
  } catch (error: any) {
    if (error.message.includes("not found")) {
      res.status(404).json({ message: error.message });
    } else {
      res.status(400).json({ message: error.message });
    }
  }
}
nyctonio commented 2 weeks ago

i am also facing a similar issue on first run the apis are running but on reload on file save i am getting 404

adrien2p commented 2 weeks ago

@renanrambul @nyctonio which version of medusa are you using?

renanrambul commented 2 weeks ago

I'm using @medusajs/medusa": "^1.20.9

I developed the same functionality in medusa v2 and didn't have this problem