Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat: enhance create command with database setup options (#656)

Jakub Sieradzki2b1b17434788
diff --git a/package-lock.json b/package-lock.json
index 03c330eae..ce1232b52 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3094,6 +3094,54 @@
"node": ">=6"
}
},
+ "node_modules/@hapi/address": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/@hapi/address/-/address-5.1.1.tgz",
+ "integrity": "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@hapi/hoek": "^11.0.2"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@hapi/formula": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@hapi/formula/-/formula-3.0.2.tgz",
+ "integrity": "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@hapi/hoek": {
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-11.0.7.tgz",
+ "integrity": "sha512-HV5undWkKzcB4RZUusqOpcgxOaq6VOAH7zhhIr2g3G8NF/MlFO75SjOr2NfuSx0Mh40+1FqCkagKLJRykUWoFQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@hapi/pinpoint": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@hapi/pinpoint/-/pinpoint-2.0.1.tgz",
+ "integrity": "sha512-EKQmr16tM8s16vTT3cA5L0kZZcTMU5DUOZTuvpnY738m+jyP3JIUj+Mm1xc1rsLkGBQ/gVnfKYPwOmPg1tUR4Q==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@hapi/tlds": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@hapi/tlds/-/tlds-1.1.4.tgz",
+ "integrity": "sha512-Fq+20dxsxLaUn5jSSWrdtSRcIUba2JquuorF9UW1wIJS5cSUwxIsO2GIhaWynPRflvxSzFN+gxKte2HEW1OuoA==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@hapi/topo": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-6.0.2.tgz",
+ "integrity": "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@hapi/hoek": "^11.0.2"
+ }
+ },
"node_modules/@hookform/error-message": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@hookform/error-message/-/error-message-2.0.1.tgz",
@@ -12399,6 +12447,12 @@
"text-hex": "1.0.x"
}
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "license": "MIT"
+ },
"node_modules/@swc/core": {
"version": "1.15.10",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.15.10.tgz",
@@ -13188,6 +13242,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/wait-on": {
+ "version": "5.3.4",
+ "resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.4.tgz",
+ "integrity": "sha512-EBsPjFMrFlMbbUFf9D1Fp+PAB2TwmUn7a3YtHyD9RLuTIk1jDd8SxXVAoez2Ciy+8Jsceo2MYEYZzJ/DvorOKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/wrap-ansi": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@types/wrap-ansi/-/wrap-ansi-3.0.0.tgz",
@@ -14533,6 +14597,21 @@
"uuid": "^9.0.0"
}
},
+ "node_modules/bundle-name": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz",
+ "integrity": "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==",
+ "license": "MIT",
+ "dependencies": {
+ "run-applescript": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/bundle-require": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",
@@ -15864,6 +15943,34 @@
"node": ">=0.10.0"
}
},
+ "node_modules/default-browser": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.4.0.tgz",
+ "integrity": "sha512-XDuvSq38Hr1MdN47EDvYtx3U0MTqpCEn+F6ft8z2vYDzMrvQhVp0ui9oQdqW3MvK3vqUETglt1tVGgjLuJ5izg==",
+ "license": "MIT",
+ "dependencies": {
+ "bundle-name": "^4.1.0",
+ "default-browser-id": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/default-browser-id": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz",
+ "integrity": "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/defaults": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",
@@ -15885,6 +15992,18 @@
"node": ">=0.8"
}
},
+ "node_modules/define-lazy-prop": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz",
+ "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -18043,6 +18162,51 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-in-ssh": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz",
+ "integrity": "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-inside-container": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz",
+ "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==",
+ "license": "MIT",
+ "dependencies": {
+ "is-docker": "^3.0.0"
+ },
+ "bin": {
+ "is-inside-container": "cli.js"
+ },
+ "engines": {
+ "node": ">=14.16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-inside-container/node_modules/is-docker": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",
+ "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==",
+ "license": "MIT",
+ "bin": {
+ "is-docker": "cli.js"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/is-interactive": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz",
@@ -20208,6 +20372,24 @@
"integrity": "sha512-8wb9Yw966OSxApiCt0K3yNJL8pnNeIv+OEq2YMidz4FKP6nonSRoOXc80iXY4JaN2FC11B9qsNmDsm+ZOfMROA==",
"license": "MIT"
},
+ "node_modules/joi": {
+ "version": "18.0.2",
+ "resolved": "https://registry.npmjs.org/joi/-/joi-18.0.2.tgz",
+ "integrity": "sha512-RuCOQMIt78LWnktPoeBL0GErkNaJPTBGcYuyaBvUOQSpcpcLfWrHPPihYdOGbV5pam9VTWbeoF7TsGiHugcjGA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@hapi/address": "^5.1.1",
+ "@hapi/formula": "^3.0.2",
+ "@hapi/hoek": "^11.0.7",
+ "@hapi/pinpoint": "^2.0.1",
+ "@hapi/tlds": "^1.1.1",
+ "@hapi/topo": "^6.0.2",
+ "@standard-schema/spec": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
"node_modules/joycon": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
@@ -21550,6 +21732,26 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/open": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/open/-/open-11.0.0.tgz",
+ "integrity": "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==",
+ "license": "MIT",
+ "dependencies": {
+ "default-browser": "^5.4.0",
+ "define-lazy-prop": "^3.0.0",
+ "is-in-ssh": "^1.0.0",
+ "is-inside-container": "^1.0.0",
+ "powershell-utils": "^0.1.0",
+ "wsl-utils": "^0.3.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -22471,6 +22673,18 @@
"node": ">=20"
}
},
+ "node_modules/powershell-utils": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.1.0.tgz",
+ "integrity": "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -23482,6 +23696,18 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/run-applescript": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz",
+ "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/run-async": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz",
@@ -25853,6 +26079,25 @@
"node": ">=0.10.0"
}
},
+ "node_modules/wait-on": {
+ "version": "9.0.3",
+ "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-9.0.3.tgz",
+ "integrity": "sha512-13zBnyYvFDW1rBvWiJ6Av3ymAaq8EDQuvxZnPIw3g04UqGi4TyoIJABmfJ6zrvKo9yeFQExNkOk7idQbDJcuKA==",
+ "license": "MIT",
+ "dependencies": {
+ "axios": "^1.13.2",
+ "joi": "^18.0.1",
+ "lodash": "^4.17.21",
+ "minimist": "^1.2.8",
+ "rxjs": "^7.8.2"
+ },
+ "bin": {
+ "wait-on": "bin/wait-on"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/walker": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz",
@@ -26030,6 +26275,37 @@
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"license": "ISC"
},
+ "node_modules/wsl-utils": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.3.1.tgz",
+ "integrity": "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==",
+ "license": "MIT",
+ "dependencies": {
+ "is-wsl": "^3.1.0",
+ "powershell-utils": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/wsl-utils/node_modules/is-wsl": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz",
+ "integrity": "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-inside-container": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/xdg-basedir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz",
@@ -26313,6 +26589,7 @@
"fast-glob": "^3.3.3",
"fs-extra": "^11.3.2",
"kleur": "^4.1.5",
+ "open": "^11.0.0",
"ora": "^9.0.0",
"pg": "^8.17.1",
"prompts": "^2.4.2",
@@ -26321,6 +26598,7 @@
"ts-morph": "^27.0.2",
"tsconfig-paths": "^4.2.0",
"validate-npm-package-name": "^7.0.2",
+ "wait-on": "^9.0.3",
"zod": "3.25.76"
},
"bin": {
@@ -26332,6 +26610,7 @@
"@types/prompts": "^2.4.9",
"@types/tar": "^6.1.13",
"@types/validate-npm-package-name": "^4.0.2",
+ "@types/wait-on": "^5.3.4",
"tsup": "^8.5.0"
}
},
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 5a119b46c..820f74490 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -31,6 +31,7 @@
"fast-glob": "^3.3.3",
"fs-extra": "^11.3.2",
"kleur": "^4.1.5",
+ "open": "^11.0.0",
"ora": "^9.0.0",
"pg": "^8.17.1",
"prompts": "^2.4.2",
@@ -39,6 +40,7 @@
"ts-morph": "^27.0.2",
"tsconfig-paths": "^4.2.0",
"validate-npm-package-name": "^7.0.2",
+ "wait-on": "^9.0.3",
"zod": "3.25.76"
},
"devDependencies": {
@@ -47,6 +49,7 @@
"@types/prompts": "^2.4.9",
"@types/tar": "^6.1.13",
"@types/validate-npm-package-name": "^4.0.2",
+ "@types/wait-on": "^5.3.4",
"tsup": "^8.5.0"
}
}
diff --git a/packages/cli/src/commands/create.ts b/packages/cli/src/commands/create.ts
index 517dd63be..6089a19a8 100644
--- a/packages/cli/src/commands/create.ts
+++ b/packages/cli/src/commands/create.ts
@@ -1,10 +1,11 @@
+import { exec } from "node:child_process";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import path from "path";
import { clearRegistryContext } from "@/src/registry/context";
import { sendTelemetryEvent, setTelemetryEmail } from "@/src/telemetry";
-import { setupDatabase } from "@/src/utils/create-db";
+import { setupDatabase, type SetupDatabaseResult } from "@/src/utils/create-db";
import { getPackageManager } from "@/src/utils/get-package-manager";
import { handleError } from "@/src/utils/handle-error";
import { highlighter } from "@/src/utils/highlighter";
@@ -15,10 +16,12 @@ import { Command } from "commander";
import { execa } from "execa";
import fs from "fs-extra";
import kleur from "kleur";
+import open from "open";
import prompts from "prompts";
import { x } from "tar";
import terminalLink from "terminal-link";
import validateProjectName from "validate-npm-package-name";
+import waitOn from "wait-on";
// todo: change to main after new release
const DEFAULT_BRANCH = "new";
@@ -42,7 +45,7 @@ export const create = new Command()
"the working directory. defaults to the current directory.",
process.cwd()
)
- .option("--no-deps", "skip installing dependencies.", false)
+ .option("--no-deps", "skip installing dependencies.")
.option("--skip-db", "skip database configuration.", false)
.option("--skip-email", "skip email prompt.", false)
.option("--db-connection-string <string>", "PostgreSQL connection string.")
@@ -50,7 +53,6 @@ export const create = new Command()
try {
validateNodeVersion();
- // Prompt for project name if not provided.
let projectName = name;
if (!projectName) {
const { enteredName } = await prompts({
@@ -76,7 +78,6 @@ export const create = new Command()
projectName = enteredName;
- // Prompt for template if not provided.
let template = opts.template;
if (!template) {
const { selectedTemplate } = await prompts({
@@ -114,16 +115,17 @@ export const create = new Command()
if (!opts.deps) {
spinner("Dependency installation skipped.").warn();
} else {
- const installSpinner = spinner("Installing dependencies...").start();
+ const initialInstallSpinner = spinner("Installing dependencies...").start();
+ const installStart = Date.now();
const result = await installDeps({
projectDir,
packageManager,
});
+ const installDuration = ((Date.now() - installStart) / 1000).toFixed(1);
if (result) {
- installSpinner.succeed("Dependencies installed successfully.");
+ initialInstallSpinner.succeed(`Dependencies installed successfully in ${installDuration}s.`);
} else {
- spinner("Failed to install dependencies.").fail();
- logger.log(feedbackOutro());
+ initialInstallSpinner.fail(`Failed to install dependencies`);
await sendTelemetryEvent({
type: 'create',
payload: {
@@ -137,20 +139,22 @@ export const create = new Command()
}
}
- // Database setup
let dbConnectionString: string | undefined = opts.dbConnectionString;
+ let dbResult: SetupDatabaseResult | undefined;
+
if (!opts.skipDb) {
const dbSpinner = spinner("Setting up database...").start();
- const dbResult = await setupDatabase({
+ dbResult = await setupDatabase({
projectDir,
projectName,
- dbConnectionString: opts.dbConnectionString,
+ dbConnectionString,
spinner: dbSpinner,
});
+
if (dbResult.success) {
if (dbResult.alreadyExists) {
dbSpinner.warn(
- `Database ${highlighter.info(dbResult.dbName)} already exists. Skipping database setup.`
+ `Database ${highlighter.info(dbResult.dbName)} already exists. Skipping database creation.`
);
} else {
dbSpinner.succeed(
@@ -166,9 +170,7 @@ export const create = new Command()
payload: {
outcome: 'database_setup_failed',
}
- }, {
- cwd: projectDir,
- })
+ }, { cwd: projectDir });
process.exit(1);
}
} else {
@@ -202,13 +204,6 @@ export const create = new Command()
databaseUri: dbConnectionString,
});
- logger.break();
- logger.info("Mercur project successfully created!");
- logger.log(kleur.bgGreen(kleur.black(" Next Steps ")));
- logger.log(successMessage(projectDir, packageManager));
- logger.log(feedbackOutro());
- logger.break();
-
await initGit(projectDir);
await sendTelemetryEvent({
@@ -218,7 +213,46 @@ export const create = new Command()
}
}, {
cwd: projectDir,
- })
+ });
+
+ spinner("Mercur project successfully created!").succeed();
+
+ if (dbResult?.success) {
+ spinner("Starting development server...").info();
+
+ const apiDir = path.join(projectDir, "packages", "api");
+ const inviteUrl = dbResult.inviteToken
+ ? `http://localhost:9000/app/invite?token=${dbResult.inviteToken}&first_run=true`
+ : "http://localhost:9000/app";
+
+ const serverProcess = exec(`${packageManager === "npm" ? "npm run" : packageManager} dev`, {
+ cwd: apiDir,
+ env: process.env,
+ });
+
+ serverProcess.stdout?.pipe(process.stdout);
+ serverProcess.stderr?.pipe(process.stderr);
+
+ waitOn({
+ resources: ["http://localhost:9000/health"],
+ timeout: 60000,
+ }).then(async () => {
+ try {
+ await open(inviteUrl);
+ } catch {
+ spinner("Open this URL in your browser to create your admin account:").info();
+ logger.log(highlighter.info(inviteUrl));
+ }
+ }).catch(() => {
+ spinner("To create your admin account, visit:").info();
+ logger.log(highlighter.info(inviteUrl));
+ });
+ } else {
+ logger.log(kleur.bgGreen(kleur.black(" Next Steps ")));
+ logger.log(successMessage(projectDir, packageManager));
+ logger.log(feedbackOutro());
+ logger.break();
+ }
}
} catch (error) {
logger.break();
@@ -288,7 +322,13 @@ async function installDeps({
}
try {
- await execa(cmd, args, { cwd: path.resolve(projectDir) });
+ await execa(cmd, args, {
+ cwd: path.resolve(projectDir),
+ stdin: "inherit",
+ stdout: "inherit",
+ stderr: "inherit",
+ env: { ...process.env, npm_config_yes: "true" },
+ });
return true;
} catch (err: unknown) {
logger.error(
@@ -351,3 +391,4 @@ function validateNodeVersion(): void {
);
}
}
+
diff --git a/packages/cli/src/utils/create-db.ts b/packages/cli/src/utils/create-db.ts
index 65b8a462a..90c57eef3 100644
--- a/packages/cli/src/utils/create-db.ts
+++ b/packages/cli/src/utils/create-db.ts
@@ -1,5 +1,6 @@
import { getPackageManager } from "@/src/utils/get-package-manager";
import { logger } from "@/src/utils/logger";
+import { manageEnvFiles } from "@/src/utils/manage-env-files";
import { spinner } from "@/src/utils/spinner";
import { execa } from "execa";
import type { Ora } from "ora";
@@ -9,12 +10,20 @@ import prompts from "prompts";
const DEFAULT_DB_HOST = "localhost";
const DEFAULT_DB_PORT = 5432;
+const API_DIR = "packages/api";
+const ADMIN_EMAIL = "[email protected]";
+
+interface DbSetupArgs {
+ projectDir: string;
+ spinner?: Ora;
+}
export interface SetupDatabaseResult {
success: boolean;
dbName: string;
connectionString: string | null;
alreadyExists?: boolean;
+ inviteToken?: string | null;
}
export async function setupDatabase(args: {
@@ -25,51 +34,43 @@ export async function setupDatabase(args: {
}): Promise<SetupDatabaseResult> {
const dbName = args.projectName.replace(/[^a-zA-Z0-9]/g, "-");
- // Try to connect and create database
const { client, dbConnectionString } = await getDbClient({
dbConnectionString: args.dbConnectionString,
spinner: args.spinner,
});
- if (!client) {
+ if (!client || !dbConnectionString) {
return { success: false, dbName, connectionString: null };
}
try {
- // Check if database already exists
+ if (args.spinner) {
+ args.spinner.text = "Checking if database exists...";
+ }
const exists = await doesDbExist(client, dbName);
if (exists) {
await client.end();
- return {
- success: true,
+ return runPostDbSetup({
+ ...args,
dbName,
connectionString: dbConnectionString,
alreadyExists: true,
- };
+ });
}
- // Create the database
+ if (args.spinner) {
+ args.spinner.text = `Creating database "${dbName}"...`;
+ }
await client.query(`CREATE DATABASE "${dbName}"`);
await client.end();
- // Run migrations
- const migrated = await runMigrations(args);
- if (!migrated) {
- return { success: false, dbName, connectionString: null };
- }
-
- // Seed database
- const seeded = await seedDatabase(args);
- if (!seeded) {
- return { success: false, dbName, connectionString: null };
- }
-
- return {
- success: true,
+ return runPostDbSetup({
+ ...args,
dbName,
connectionString: dbConnectionString,
- };
+ alreadyExists: false,
+ });
} catch (err) {
logger.error(
`Error creating database${err instanceof Error ? `: ${err.message}` : ""}.`
@@ -79,23 +80,57 @@ export async function setupDatabase(args: {
}
}
+async function runPostDbSetup(args: DbSetupArgs & {
+ dbName: string;
+ connectionString: string;
+ alreadyExists: boolean;
+}): Promise<SetupDatabaseResult> {
+ const { projectDir, spinner, dbName, connectionString, alreadyExists } = args;
+
+ // Medusa needs DATABASE_URL in .env before running migrations
+ await manageEnvFiles({
+ projectDir,
+ databaseUri: connectionString,
+ });
+
+ const migrated = await runMigrations({ projectDir, spinner });
+ if (!migrated) {
+ return { success: false, dbName, connectionString: null };
+ }
+
+ const seeded = await seedDatabase({ projectDir });
+ if (!seeded) {
+ return { success: false, dbName, connectionString: null };
+ }
+
+ const inviteToken = await createAdminInvite({ projectDir });
+
+ return {
+ success: true,
+ dbName,
+ connectionString,
+ alreadyExists,
+ inviteToken,
+ };
+}
+
+interface DbClientResult {
+ client: pg.Client | null;
+ dbConnectionString: string | null;
+}
+
async function getDbClient({
dbConnectionString,
spinner: spinnerRef,
}: {
dbConnectionString?: string;
spinner?: Ora;
-}): Promise<{
- client: pg.Client | null;
- dbConnectionString: string | null;
-}> {
- // If connection string provided, try to use it
+}): Promise<DbClientResult> {
if (dbConnectionString) {
try {
- return {
- client: new pg.Client({ connectionString: dbConnectionString }),
- dbConnectionString,
- };
+ const client = new pg.Client({ connectionString: dbConnectionString });
+ await client.connect();
+ return { client, dbConnectionString };
} catch (error) {
logger.error(
`Invalid database connection string${error instanceof Error ? `: ${error.message}` : ""}.`
@@ -107,7 +142,6 @@ async function getDbClient({
let postgresUsername = "postgres";
let postgresPassword = "";
- // If no connection string provided, try default connection
try {
const defaultCredentials = {
user: postgresUsername,
@@ -124,10 +158,8 @@ async function getDbClient({
dbConnectionString: formatConnectionString(defaultCredentials),
};
} catch {
- // Stop spinner before prompts
spinnerRef?.stop();
- // Ask for credentials
const answers = await prompts([
{
type: "text",
@@ -149,7 +181,6 @@ async function getDbClient({
postgresUsername = answers.postgresUsername;
postgresPassword = answers.postgresPassword || "";
- // Restart spinner after prompts
spinnerRef?.start("Connecting to database...");
try {
@@ -207,34 +238,21 @@ function formatConnectionString({
return `postgresql://${user}:${encodedPassword}@${host}:${port}/${db}`;
}
-async function runMigrations({
- projectDir,
-}: {
- projectDir: string;
-}): Promise<boolean> {
- const apiDir = path.join(projectDir, "apps", "api");
- const packageManager = await getPackageManager(apiDir);
-
- const migrationSpinner = spinner("Running db:migrate command...").start();
+async function runMigrations({ projectDir, spinner: parentSpinner }: DbSetupArgs): Promise<boolean> {
+ const apiDir = path.join(projectDir, API_DIR);
+ const migrationSpinner = parentSpinner || spinner("Running migrations...").start();
try {
- let migrateCmd: string[];
-
- if (packageManager === "yarn") {
- migrateCmd = ["yarn", "db:migrate"];
- } else if (packageManager === "pnpm") {
- migrateCmd = ["pnpm", "run", "db:migrate"];
- } else if (packageManager === "bun") {
- migrateCmd = ["bun", "run", "db:migrate"];
- } else {
- migrateCmd = ["npm", "run", "db:migrate"];
- }
+ // Build first - compiles TypeScript so ts-node is not needed
+ migrationSpinner.text = "Building project...";
+ await execa("npm", ["run", "build"], { cwd: apiDir });
- await execa(migrateCmd[0], migrateCmd.slice(1), {
- cwd: apiDir,
- });
+ migrationSpinner.text = "Running database migrations...";
+ await execa("npx", ["medusa", "db:migrate"], { cwd: apiDir });
- migrationSpinner.succeed("Migrations completed successfully.");
+ if (!parentSpinner) {
+ migrationSpinner.succeed("Migrations completed successfully.");
+ }
return true;
} catch (err) {
migrationSpinner.fail("Failed to run migrations.");
@@ -245,33 +263,41 @@ async function runMigrations({
}
}
-async function seedDatabase({
- projectDir,
-}: {
- projectDir: string;
-}): Promise<boolean> {
- const apiDir = path.join(projectDir, "apps", "api");
- const packageManager = await getPackageManager(apiDir);
-
- const seedSpinner = spinner("Running db:seed command...").start();
+async function createAdminInvite({ projectDir }: { projectDir: string }): Promise<string | null> {
+ const apiDir = path.join(projectDir, API_DIR);
try {
- let seedCmd: string[];
-
- if (packageManager === "yarn") {
- seedCmd = ["yarn", "seed"];
- } else if (packageManager === "pnpm") {
- seedCmd = ["pnpm", "run", "seed"];
- } else if (packageManager === "bun") {
- seedCmd = ["bun", "run", "seed"];
- } else {
- seedCmd = ["npm", "run", "seed"];
- }
-
- await execa(seedCmd[0], seedCmd.slice(1), {
+ const result = await execa("npx", ["medusa", "user", "-e", ADMIN_EMAIL, "--invite"], {
cwd: apiDir,
});
+ // Parse token from stdout - same approach as Medusa CLI
+ const match = result.stdout.match(/Invite token: (?<token>.+)/);
+ return match?.groups?.token || null;
+ } catch (err) {
+ logger.error(
+ `Error creating admin invite${err instanceof Error ? `: ${err.message}` : ""}.`
+ );
+ return null;
+ }
+}
+
+async function seedDatabase({ projectDir }: { projectDir: string }): Promise<boolean> {
+ const apiDir = path.join(projectDir, API_DIR);
+ const packageManager = await getPackageManager(apiDir);
+ const seedSpinner = spinner("Seeding database...").start();
+
+ try {
+ const seedCmd = packageManager === "yarn"
+ ? ["yarn", "seed"]
+ : packageManager === "pnpm"
+ ? ["pnpm", "run", "seed"]
+ : packageManager === "bun"
+ ? ["bun", "run", "seed"]
+ : ["npm", "run", "seed"];
+
+ await execa(seedCmd[0], seedCmd.slice(1), { cwd: apiDir });
+
seedSpinner.succeed("Database seeded successfully.");
return true;
} catch (err) {
diff --git a/templates/basic/packages/api/src/scripts/seed.ts b/templates/basic/packages/api/src/scripts/seed.ts
index d76880c18..d8f863d80 100644
--- a/templates/basic/packages/api/src/scripts/seed.ts
+++ b/templates/basic/packages/api/src/scripts/seed.ts
@@ -111,48 +111,110 @@ export default async function seedDemoData({ container }: ExecArgs) {
},
});
logger.info("Seeding region data...");
- const { result: regionResult } = await createRegionsWorkflow(container).run({
- input: {
- regions: [
- {
- name: "Europe",
- currency_code: "eur",
- countries,
- payment_providers: ["pp_system_default"],
- },
- ],
- },
+ const regionModuleService = container.resolve(Modules.REGION);
+
+ // Check if any of the countries are already assigned to a region
+ const existingRegions = await regionModuleService.listRegions({}, {
+ relations: ["countries"],
});
- const region = regionResult[0];
+
+ const assignedCountries = new Set<string>();
+ for (const r of existingRegions) {
+ for (const c of r.countries || []) {
+ assignedCountries.add(c.iso_2);
+ }
+ }
+
+ const unassignedCountries = countries.filter(c => !assignedCountries.has(c));
+
+ let region;
+ if (unassignedCountries.length === 0) {
+ // All countries already assigned - find the region that has most of our countries
+ region = existingRegions.find(r =>
+ r.countries?.some(c => countries.includes(c.iso_2))
+ ) || existingRegions[0];
+ logger.info("Countries already assigned to a region, skipping region creation.");
+ } else if (unassignedCountries.length < countries.length) {
+ // Some countries assigned, some not - only create with unassigned ones
+ logger.info(`Some countries already assigned, creating region with: ${unassignedCountries.join(", ")}`);
+ const { result: regionResult } = await createRegionsWorkflow(container).run({
+ input: {
+ regions: [
+ {
+ name: "Europe",
+ currency_code: "eur",
+ countries: unassignedCountries,
+ payment_providers: ["pp_system_default"],
+ },
+ ],
+ },
+ });
+ region = regionResult[0];
+ } else {
+ // No countries assigned - create full region
+ const { result: regionResult } = await createRegionsWorkflow(container).run({
+ input: {
+ regions: [
+ {
+ name: "Europe",
+ currency_code: "eur",
+ countries,
+ payment_providers: ["pp_system_default"],
+ },
+ ],
+ },
+ });
+ region = regionResult[0];
+ }
logger.info("Finished seeding regions.");
logger.info("Seeding tax regions...");
- await createTaxRegionsWorkflow(container).run({
- input: countries.map((country_code) => ({
- country_code,
- provider_id: "tp_system",
- })),
- });
+ const taxModuleService = container.resolve(Modules.TAX);
+ const existingTaxRegions = await taxModuleService.listTaxRegions();
+ const existingCountryCodes = new Set(existingTaxRegions.map((tr) => tr.country_code));
+ const countriesToCreate = countries.filter((c) => !existingCountryCodes.has(c));
+
+ if (countriesToCreate.length > 0) {
+ await createTaxRegionsWorkflow(container).run({
+ input: countriesToCreate.map((country_code) => ({
+ country_code,
+ provider_id: "tp_system",
+ })),
+ });
+ } else {
+ logger.info("Tax regions already exist, skipping.");
+ }
logger.info("Finished seeding tax regions.");
logger.info("Seeding stock location data...");
- const { result: stockLocationResult } = await createStockLocationsWorkflow(
- container
- ).run({
- input: {
- locations: [
- {
- name: "European Warehouse",
- address: {
- city: "Copenhagen",
- country_code: "DK",
- address_1: "",
- },
- },
- ],
- },
+ const stockLocationModule = container.resolve(Modules.STOCK_LOCATION);
+ const existingStockLocations = await stockLocationModule.listStockLocations({
+ name: "European Warehouse",
});
- const stockLocation = stockLocationResult[0];
+
+ let stockLocation;
+ if (existingStockLocations.length) {
+ stockLocation = existingStockLocations[0];
+ logger.info("Stock location 'European Warehouse' already exists, skipping.");
+ } else {
+ const { result: stockLocationResult } = await createStockLocationsWorkflow(
+ container
+ ).run({
+ input: {
+ locations: [
+ {
+ name: "European Warehouse",
+ address: {
+ city: "Copenhagen",
+ country_code: "DK",
+ address_1: "",
+ },
+ },
+ ],
+ },
+ });
+ stockLocation = stockLocationResult[0];
+ }
await updateStoresWorkflow(container).run({
input: {
@@ -163,14 +225,23 @@ export default async function seedDemoData({ container }: ExecArgs) {
},
});
- await link.create({
- [Modules.STOCK_LOCATION]: {
- stock_location_id: stockLocation.id,
- },
- [Modules.FULFILLMENT]: {
- fulfillment_provider_id: "manual_manual",
- },
- });
+ // Link stock location to fulfillment provider (idempotent)
+ try {
+ await link.create({
+ [Modules.STOCK_LOCATION]: {
+ stock_location_id: stockLocation.id,
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_provider_id: "manual_manual",
+ },
+ });
+ } catch (error: unknown) {
+ // Ignore if link already exists
+ if (!(error instanceof Error && error.message.includes("already exists"))) {
+ throw error;
+ }
+ logger.info("Stock location already linked to fulfillment provider, skipping.");
+ }
logger.info("Seeding fulfillment data...");
const shippingProfiles = await fulfillmentModuleService.listShippingProfiles({
@@ -193,143 +264,168 @@ export default async function seedDemoData({ container }: ExecArgs) {
shippingProfile = shippingProfileResult[0];
}
- const fulfillmentSet = await fulfillmentModuleService.createFulfillmentSets({
+ const existingFulfillmentSets = await fulfillmentModuleService.listFulfillmentSets({
name: "European Warehouse delivery",
- type: "shipping",
- service_zones: [
- {
- name: "Europe",
- geo_zones: [
- {
- country_code: "gb",
- type: "country",
- },
- {
- country_code: "de",
- type: "country",
- },
- {
- country_code: "dk",
- type: "country",
- },
- {
- country_code: "se",
- type: "country",
- },
- {
- country_code: "fr",
- type: "country",
- },
- {
- country_code: "es",
- type: "country",
- },
- {
- country_code: "it",
- type: "country",
- },
- ],
- },
- ],
});
- await link.create({
- [Modules.STOCK_LOCATION]: {
- stock_location_id: stockLocation.id,
- },
- [Modules.FULFILLMENT]: {
- fulfillment_set_id: fulfillmentSet.id,
- },
- });
+ let fulfillmentSet;
+ if (existingFulfillmentSets.length) {
+ fulfillmentSet = existingFulfillmentSets[0];
+ logger.info("Fulfillment set 'European Warehouse delivery' already exists, skipping.");
+ } else {
+ fulfillmentSet = await fulfillmentModuleService.createFulfillmentSets({
+ name: "European Warehouse delivery",
+ type: "shipping",
+ service_zones: [
+ {
+ name: "Europe",
+ geo_zones: [
+ {
+ country_code: "gb",
+ type: "country",
+ },
+ {
+ country_code: "de",
+ type: "country",
+ },
+ {
+ country_code: "dk",
+ type: "country",
+ },
+ {
+ country_code: "se",
+ type: "country",
+ },
+ {
+ country_code: "fr",
+ type: "country",
+ },
+ {
+ country_code: "es",
+ type: "country",
+ },
+ {
+ country_code: "it",
+ type: "country",
+ },
+ ],
+ },
+ ],
+ });
- await createShippingOptionsWorkflow(container).run({
- input: [
- {
- name: "Standard Shipping",
- price_type: "flat",
- provider_id: "manual_manual",
- service_zone_id: fulfillmentSet.service_zones[0].id,
- shipping_profile_id: shippingProfile.id,
- type: {
- label: "Standard",
- description: "Ship in 2-3 days.",
- code: "standard",
+ try {
+ await link.create({
+ [Modules.STOCK_LOCATION]: {
+ stock_location_id: stockLocation.id,
},
- prices: [
- {
- currency_code: "usd",
- amount: 10,
- },
- {
- currency_code: "eur",
- amount: 10,
- },
- {
- region_id: region.id,
- amount: 10,
- },
- ],
- rules: [
- {
- attribute: "enabled_in_store",
- value: "true",
- operator: "eq",
- },
- {
- attribute: "is_return",
- value: "false",
- operator: "eq",
- },
- ],
- },
- {
- name: "Express Shipping",
- price_type: "flat",
- provider_id: "manual_manual",
- service_zone_id: fulfillmentSet.service_zones[0].id,
- shipping_profile_id: shippingProfile.id,
- type: {
- label: "Express",
- description: "Ship in 24 hours.",
- code: "express",
+ [Modules.FULFILLMENT]: {
+ fulfillment_set_id: fulfillmentSet.id,
},
- prices: [
- {
- currency_code: "usd",
- amount: 10,
- },
- {
- currency_code: "eur",
- amount: 10,
- },
- {
- region_id: region.id,
- amount: 10,
- },
- ],
- rules: [
- {
- attribute: "enabled_in_store",
- value: "true",
- operator: "eq",
+ });
+ } catch (error: unknown) {
+ if (!(error instanceof Error && error.message.includes("already exists"))) {
+ throw error;
+ }
+ }
+
+ await createShippingOptionsWorkflow(container).run({
+ input: [
+ {
+ name: "Standard Shipping",
+ price_type: "flat",
+ provider_id: "manual_manual",
+ service_zone_id: fulfillmentSet.service_zones[0].id,
+ shipping_profile_id: shippingProfile.id,
+ type: {
+ label: "Standard",
+ description: "Ship in 2-3 days.",
+ code: "standard",
},
- {
- attribute: "is_return",
- value: "false",
- operator: "eq",
+ prices: [
+ {
+ currency_code: "usd",
+ amount: 10,
+ },
+ {
+ currency_code: "eur",
+ amount: 10,
+ },
+ {
+ region_id: region.id,
+ amount: 10,
+ },
+ ],
+ rules: [
+ {
+ attribute: "enabled_in_store",
+ value: "true",
+ operator: "eq",
+ },
+ {
+ attribute: "is_return",
+ value: "false",
+ operator: "eq",
+ },
+ ],
+ },
+ {
+ name: "Express Shipping",
+ price_type: "flat",
+ provider_id: "manual_manual",
+ service_zone_id: fulfillmentSet.service_zones[0].id,
+ shipping_profile_id: shippingProfile.id,
+ type: {
+ label: "Express",
+ description: "Ship in 24 hours.",
+ code: "express",
},
- ],
- },
- ],
- });
+ prices: [
+ {
+ currency_code: "usd",
+ amount: 10,
+ },
+ {
+ currency_code: "eur",
+ amount: 10,
+ },
+ {
+ region_id: region.id,
+ amount: 10,
+ },
+ ],
+ rules: [
+ {
+ attribute: "enabled_in_store",
+ value: "true",
+ operator: "eq",
+ },
+ {
+ attribute: "is_return",
+ value: "false",
+ operator: "eq",
+ },
+ ],
+ },
+ ],
+ });
+ }
logger.info("Finished seeding fulfillment data.");
- await linkSalesChannelsToStockLocationWorkflow(container).run({
- input: {
- id: stockLocation.id,
- add: [defaultSalesChannel[0].id],
- },
- });
+ // Link sales channel to stock location (idempotent - workflow handles duplicates)
+ try {
+ await linkSalesChannelsToStockLocationWorkflow(container).run({
+ input: {
+ id: stockLocation.id,
+ add: [defaultSalesChannel[0].id],
+ },
+ });
+ } catch (error: unknown) {
+ // Ignore if link already exists
+ if (!(error instanceof Error && error.message.includes("already"))) {
+ throw error;
+ }
+ logger.info("Sales channel already linked to stock location, skipping.");
+ }
logger.info("Finished seeding stock location data.");
logger.info("Seeding publishable API key data...");
@@ -362,49 +458,68 @@ export default async function seedDemoData({ container }: ExecArgs) {
publishableApiKey = publishableApiKeyResult as ApiKey;
}
- await linkSalesChannelsToApiKeyWorkflow(container).run({
- input: {
- id: publishableApiKey.id,
- add: [defaultSalesChannel[0].id],
- },
- });
+ // Link sales channel to API key (idempotent)
+ try {
+ await linkSalesChannelsToApiKeyWorkflow(container).run({
+ input: {
+ id: publishableApiKey.id,
+ add: [defaultSalesChannel[0].id],
+ },
+ });
+ } catch (error: unknown) {
+ // Ignore if link already exists
+ if (!(error instanceof Error && error.message.includes("already"))) {
+ throw error;
+ }
+ logger.info("Sales channel already linked to API key, skipping.");
+ }
logger.info("Finished seeding publishable API key data.");
logger.info("Seeding product data...");
- const { result: categoryResult } = await createProductCategoriesWorkflow(
- container
- ).run({
- input: {
- product_categories: [
- {
- name: "Shirts",
- is_active: true,
- },
- {
- name: "Sweatshirts",
- is_active: true,
- },
- {
- name: "Pants",
- is_active: true,
- },
- {
- name: "Merch",
+ const productCategoryModule = container.resolve(Modules.PRODUCT);
+ const categoryNames = ["Shirts", "Sweatshirts", "Pants", "Merch"];
+ const existingCategories = await productCategoryModule.listProductCategories({
+ name: categoryNames,
+ });
+
+ let categoryResult;
+ if (existingCategories.length === categoryNames.length) {
+ categoryResult = existingCategories;
+ logger.info("Product categories already exist, skipping.");
+ } else {
+ const categoriesToCreate = categoryNames.filter(
+ (name) => !existingCategories.find((c) => c.name === name)
+ );
+ const { result: newCategories } = await createProductCategoriesWorkflow(
+ container
+ ).run({
+ input: {
+ product_categories: categoriesToCreate.map((name) => ({
+ name,
is_active: true,
- },
- ],
- },
+ })),
+ },
+ });
+ categoryResult = [...existingCategories, ...newCategories];
+ }
+
+ const productHandles = ["t-shirt", "sweatshirt", "sweatpants", "shorts"];
+ const existingProducts = await productCategoryModule.listProducts({
+ handle: productHandles,
});
- await createProductsWorkflow(container).run({
- input: {
- products: [
- {
- title: "Medusa T-Shirt",
- category_ids: [
- categoryResult.find((cat) => cat.name === "Shirts")!.id,
- ],
+ if (existingProducts.length === productHandles.length) {
+ logger.info("Products already exist, skipping.");
+ } else {
+ await createProductsWorkflow(container).run({
+ input: {
+ products: [
+ {
+ title: "Medusa T-Shirt",
+ category_ids: [
+ categoryResult.find((cat: { name: string }) => cat.name === "Shirts")!.id,
+ ],
description:
"Reimagine the feeling of a classic T-shirt. With our cotton T-shirts, everyday essentials no longer have to be ordinary.",
handle: "t-shirt",
@@ -590,7 +705,7 @@ export default async function seedDemoData({ container }: ExecArgs) {
{
title: "Medusa Sweatshirt",
category_ids: [
- categoryResult.find((cat) => cat.name === "Sweatshirts")!.id,
+ categoryResult.find((cat: { name: string }) => cat.name === "Sweatshirts")!.id,
],
description:
"Reimagine the feeling of a classic sweatshirt. With our cotton sweatshirt, everyday essentials no longer have to be ordinary.",
@@ -691,7 +806,7 @@ export default async function seedDemoData({ container }: ExecArgs) {
{
title: "Medusa Sweatpants",
category_ids: [
- categoryResult.find((cat) => cat.name === "Pants")!.id,
+ categoryResult.find((cat: { name: string }) => cat.name === "Pants")!.id,
],
description:
"Reimagine the feeling of classic sweatpants. With our cotton sweatpants, everyday essentials no longer have to be ordinary.",
@@ -792,7 +907,7 @@ export default async function seedDemoData({ container }: ExecArgs) {
{
title: "Medusa Shorts",
category_ids: [
- categoryResult.find((cat) => cat.name === "Merch")!.id,
+ categoryResult.find((cat: { name: string }) => cat.name === "Merch")!.id,
],
description:
"Reimagine the feeling of classic shorts. With our cotton shorts, everyday essentials no longer have to be ordinary.",
@@ -892,7 +1007,8 @@ export default async function seedDemoData({ container }: ExecArgs) {
},
],
},
- });
+ });
+ }
logger.info("Finished seeding product data.");
logger.info("Seeding inventory levels.");
@@ -902,21 +1018,33 @@ export default async function seedDemoData({ container }: ExecArgs) {
fields: ["id"],
});
+ const inventoryModule = container.resolve(Modules.INVENTORY);
+ const existingLevels = await inventoryModule.listInventoryLevels({
+ location_id: stockLocation.id,
+ });
+ const existingItemIds = new Set(existingLevels.map((l) => l.inventory_item_id));
+
const inventoryLevels: CreateInventoryLevelInput[] = [];
for (const inventoryItem of inventoryItems) {
- const inventoryLevel = {
- location_id: stockLocation.id,
- stocked_quantity: 1000000,
- inventory_item_id: inventoryItem.id,
- };
- inventoryLevels.push(inventoryLevel);
+ if (!existingItemIds.has(inventoryItem.id)) {
+ const inventoryLevel = {
+ location_id: stockLocation.id,
+ stocked_quantity: 1000000,
+ inventory_item_id: inventoryItem.id,
+ };
+ inventoryLevels.push(inventoryLevel);
+ }
}
- await createInventoryLevelsWorkflow(container).run({
- input: {
- inventory_levels: inventoryLevels,
- },
- });
+ if (inventoryLevels.length > 0) {
+ await createInventoryLevelsWorkflow(container).run({
+ input: {
+ inventory_levels: inventoryLevels,
+ },
+ });
+ } else {
+ logger.info("Inventory levels already exist, skipping.");
+ }
logger.info("Finished seeding inventory levels data.");
}