Hello from MCP server

List Files | Just Commands | Repo | Logs

← back |
import { spawn } from "child_process";
import getPort from "get-port";
import path from "path";
import { rmSync } from "fs";
import fs from "fs";

async function buildGoProject() {
  const goBinary = "go";
  const projectDir = path.resolve("../../backend");
  const outputPath = path.join(projectDir, "./", "pricebook-platform");

  return new Promise((resolve, reject) => {
    const build = spawn(goBinary, ["build", "-o", outputPath], {
      cwd: projectDir,
      stdio: "inherit",
    });

    build.on("exit", (code) => {
      if (code === 0) {
        console.log(`✅ Build complete at ${outputPath}`);
        resolve();
      } else {
        reject(new Error(`❌ Build failed with exit code ${code}`));
      }
    });
  });
}

export async function startPocketBase(flags) {
  await buildGoProject();
  console.log("Start PocketBase");
  const pbPath = path.resolve("../../backend/pricebook-platform");

  let port;
  let testDir;

  if (flags.dev) {
    port = 8090;
    testDir = path.resolve("../../backend/pb_data");
  } else {
    port = await getPort();
    testDir = path.resolve("../../backend/test_data");
    rmSync(testDir, { recursive: true, force: true });
  }

  // Create superuser before server starts
  const upsert = spawn(pbPath, [
    "--dir",
    testDir,
    "superuser",
    "upsert",
    "admin@example.com",
    "0123456789",
  ]);

  await new Promise((res) => upsert.on("exit", res));

  const logFile = "../../logs/pocketbase.log";

  const logStream = fs.createWriteStream(logFile, { flags: "a" });

  const pbProcess = spawn(
    pbPath,
    ["serve", "--http", `127.0.0.1:${port}`, "--dir", testDir, "--dev"],
    {
      stdio: ["ignore", "pipe", "pipe"],
    },
  );

  // Redirect stdout and stderr to log file
  pbProcess.stdout.pipe(logStream);
  pbProcess.stderr.pipe(logStream);

  // Graceful shutdown on test exit
  process.on("exit", () => pbProcess.kill());
  process.on("SIGINT", () => pbProcess.kill());
  process.on("SIGTERM", () => pbProcess.kill());

  // Wait for PocketBase to be ready
  await new Promise((resolve) => setTimeout(resolve, 3000));

  return { port, testDir, process: pbProcess };
}