Browse Source

feat(core): Expose init CLI command

Used to populate initial data like countries & tax rates
Michael Bromley 6 years ago
parent
commit
4d5f0d910c
2 changed files with 28 additions and 8 deletions
  1. 13 7
      packages/core/cli/populate.ts
  2. 15 1
      packages/core/cli/vendure-cli.ts

+ 13 - 7
packages/core/cli/populate.ts

@@ -29,7 +29,7 @@ export async function populate(
         throw new Error('Could not bootstrap the Vendure app');
     }
     const initialData = require(initialDataPath);
-    await populateInitialData(app, initialData);
+    await populateInitialData(initialData, app);
     if (productsCsvPath) {
         await importProductsFromFile(app, productsCsvPath, initialData.defaultLanguage);
         await populateCollections(app, initialData);
@@ -104,13 +104,19 @@ async function getApplicationRef(): Promise<INestApplication | undefined> {
     return app;
 }
 
-async function populateInitialData(app: INestApplication, initialData: object) {
-    const populator = app.get(Populator);
-    try {
-        await populator.populateInitialData(initialData);
-    } catch (err) {
-        console.error(err.message);
+export async function populateInitialData(initialData: object, app?: INestApplication) {
+    if (!app) {
+        app = await getApplicationRef();
     }
+    if (app) {
+        const populator = app.get(Populator);
+        try {
+            await populator.populateInitialData(initialData);
+        } catch (err) {
+            console.error(err.message);
+        }
+    }
+    return app;
 }
 
 async function populateCollections(app: INestApplication, initialData: object) {

+ 15 - 1
packages/core/cli/vendure-cli.ts

@@ -3,7 +3,7 @@ import program from 'commander';
 import path from 'path';
 
 import { logColored } from './cli-utils';
-import { importProducts } from './populate';
+import { importProducts, populateInitialData } from './populate';
 // tslint:disable-next-line:no-var-requires
 const version = require('../../package.json').version;
 
@@ -26,6 +26,20 @@ program
         const filePath = path.join(process.cwd(), csvPath);
         await importProducts(filePath, command.language);
     });
+program
+    .command('init <initDataFile>')
+    .description('Import initial data from the specified json file')
+    .action(async (initDataFile, command) => {
+        const filePath = path.join(process.cwd(), initDataFile);
+        logColored(`\nPopulating initial data from "${filePath}"...\n`);
+        const initialData = require(filePath);
+        const app = await populateInitialData(initialData);
+        logColored('\nDone!');
+        if (app) {
+            await app.close();
+        }
+        process.exit(0);
+    });
 program.parse(process.argv);
 if (!process.argv.slice(2).length) {
     program.help();