populate.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import { INestApplication } from '@nestjs/common';
  2. import fs from 'fs-extra';
  3. import path from 'path';
  4. import { logColored } from './cli-utils';
  5. // tslint:disable:no-var-requires
  6. let Populator: any;
  7. let Importer: any;
  8. try {
  9. Populator = require('@vendure/core').Populator;
  10. Importer = require('@vendure/core').Importer;
  11. } catch (e) {
  12. Populator = require('../src/data-import/providers/populator/populator').Populator;
  13. Importer = require('../src/data-import/providers/importer/importer').Importer;
  14. }
  15. // tslint:disable:no-console
  16. /**
  17. * Populates the Vendure server with some initial data and (optionally) product data from
  18. * a supplied CSV file.
  19. */
  20. export async function populate(
  21. bootstrapFn: () => Promise<INestApplication | undefined>,
  22. initialDataPathOrObject: string | object,
  23. productsCsvPath?: string,
  24. ): Promise<INestApplication> {
  25. const app = await bootstrapFn();
  26. if (!app) {
  27. throw new Error('Could not bootstrap the Vendure app');
  28. }
  29. const initialData =
  30. typeof initialDataPathOrObject === 'string'
  31. ? require(initialDataPathOrObject)
  32. : initialDataPathOrObject;
  33. await populateInitialData(app, initialData);
  34. if (productsCsvPath) {
  35. await importProductsFromFile(app, productsCsvPath, initialData.defaultLanguage);
  36. await populateCollections(app, initialData);
  37. }
  38. logColored('\nDone!');
  39. return app;
  40. }
  41. export async function importProducts(csvPath: string, languageCode: string) {
  42. logColored(`\nImporting from "${csvPath}"...\n`);
  43. const app = await getApplicationRef();
  44. if (app) {
  45. await importProductsFromFile(app, csvPath, languageCode);
  46. logColored('\nDone!');
  47. await app.close();
  48. process.exit(0);
  49. }
  50. }
  51. export async function getApplicationRef(): Promise<INestApplication | undefined> {
  52. const tsConfigFile = path.join(process.cwd(), 'vendure-config.ts');
  53. const jsConfigFile = path.join(process.cwd(), 'vendure-config.js');
  54. let isTs = false;
  55. let configFile: string | undefined;
  56. if (fs.existsSync(tsConfigFile)) {
  57. configFile = tsConfigFile;
  58. isTs = true;
  59. } else if (fs.existsSync(jsConfigFile)) {
  60. configFile = jsConfigFile;
  61. }
  62. if (!configFile) {
  63. console.error(`Could not find a config file`);
  64. console.error(`Checked "${tsConfigFile}", "${jsConfigFile}"`);
  65. process.exit(1);
  66. return;
  67. }
  68. if (isTs) {
  69. // we expect ts-node to be available
  70. const tsNode = require('ts-node');
  71. if (!tsNode) {
  72. console.error(`For "populate" to work with TypeScript projects, you must have ts-node installed`);
  73. process.exit(1);
  74. return;
  75. }
  76. require('ts-node').register();
  77. }
  78. const index = require(configFile);
  79. if (!index) {
  80. console.error(`Could not read the contents of "${configFile}"`);
  81. process.exit(1);
  82. return;
  83. }
  84. if (!index.config) {
  85. console.error(`The file "${configFile}" does not export a "config" object`);
  86. process.exit(1);
  87. return;
  88. }
  89. const config = index.config;
  90. // Force the sync mode on, so that all the tables are created
  91. // on this initial run.
  92. config.dbConnectionOptions.synchronize = true;
  93. const { bootstrap } = require('@vendure/core');
  94. console.log('Bootstrapping Vendure server...');
  95. const app = await bootstrap(config);
  96. return app;
  97. }
  98. export async function populateInitialData(app: INestApplication, initialData: object) {
  99. const populator = app.get(Populator);
  100. try {
  101. await populator.populateInitialData(initialData);
  102. } catch (err) {
  103. console.error(err.message);
  104. }
  105. }
  106. export async function populateCollections(app: INestApplication, initialData: { collections: any[] }) {
  107. const populator = app.get(Populator);
  108. try {
  109. if (initialData.collections.length) {
  110. logColored(`Populating ${initialData.collections.length} Collections...`);
  111. await populator.populateCollections(initialData);
  112. }
  113. } catch (err) {
  114. console.error(err.message);
  115. }
  116. }
  117. async function importProductsFromFile(app: INestApplication, csvPath: string, languageCode: string) {
  118. // import the csv of same product data
  119. const importer = app.get(Importer);
  120. const productData = await fs.readFile(csvPath, 'utf-8');
  121. const importResult = await importer.parseAndImport(productData, languageCode, true).toPromise();
  122. if (importResult.errors.length) {
  123. const errorFile = path.join(process.cwd(), 'vendure-import-error.log');
  124. console.log(
  125. `${importResult.errors.length} errors encountered when importing product data. See: ${errorFile}`,
  126. );
  127. await fs.writeFile(errorFile, importResult.errors.join('\n'));
  128. }
  129. logColored(`\nImported ${importResult.imported} products`);
  130. }