index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { Router } from "express";
  2. import cors from "cors";
  3. import bodyParser from "body-parser";
  4. import { authenticate, ConfigModule } from "@medusajs/medusa";
  5. import { getConfigFile } from "medusa-core-utils";
  6. import { attachStoreRoutes } from "./routes/store";
  7. import { attachAdminRoutes } from "./routes/admin";
  8. export default (rootDirectory: string): Router | Router[] => {
  9. // Read currently-loaded medusa config
  10. const { configModule } = getConfigFile<ConfigModule>(
  11. rootDirectory,
  12. "medusa-config"
  13. );
  14. const { projectConfig } = configModule;
  15. // Set up our CORS options objects, based on config
  16. const storeCorsOptions = {
  17. origin: projectConfig.store_cors.split(","),
  18. credentials: true,
  19. };
  20. const adminCorsOptions = {
  21. origin: projectConfig.admin_cors.split(","),
  22. credentials: true,
  23. };
  24. // Set up express router
  25. const router = Router();
  26. // Set up root routes for store and admin endpoints, with appropriate CORS settings
  27. router.use("/store", cors(storeCorsOptions), bodyParser.json());
  28. router.use("/admin", cors(adminCorsOptions), bodyParser.json());
  29. // Add authentication to all admin routes *except* auth and account invite ones
  30. router.use(/\/admin\/((?!auth)(?!invites).*)/, authenticate());
  31. // Set up routers for store and admin endpoints
  32. const storeRouter = Router();
  33. const adminRouter = Router();
  34. // Attach these routers to the root routes
  35. router.use("/store", storeRouter);
  36. router.use("/admin", adminRouter);
  37. // Attach custom routes to these routers
  38. attachStoreRoutes(storeRouter);
  39. attachAdminRoutes(adminRouter);
  40. return router;
  41. };