populate.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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. initialDataPath: string,
  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 = require(initialDataPath);
  30. await populateInitialData(app, initialData);
  31. if (productsCsvPath) {
  32. await importProductsFromFile(app, productsCsvPath, initialData.defaultLanguage);
  33. await populateCollections(app, initialData);
  34. }
  35. logColored('\nDone!');
  36. return app;
  37. }
  38. export async function importProducts(csvPath: string, languageCode: string) {
  39. logColored(`\nImporting from "${csvPath}"...\n`);
  40. const app = await getApplicationRef();
  41. if (app) {
  42. await importProductsFromFile(app, csvPath, languageCode);
  43. logColored('\nDone!');
  44. await app.close();
  45. process.exit(0);
  46. }
  47. }
  48. export async function getApplicationRef(): Promise<INestApplication | undefined> {
  49. const tsConfigFile = path.join(process.cwd(), 'vendure-config.ts');
  50. const jsConfigFile = path.join(process.cwd(), 'vendure-config.js');
  51. let isTs = false;
  52. let configFile: string | undefined;
  53. if (fs.existsSync(tsConfigFile)) {
  54. configFile = tsConfigFile;
  55. isTs = true;
  56. } else if (fs.existsSync(jsConfigFile)) {
  57. configFile = jsConfigFile;
  58. }
  59. if (!configFile) {
  60. console.error(`Could not find a config file`);
  61. console.error(`Checked "${tsConfigFile}", "${jsConfigFile}"`);
  62. process.exit(1);
  63. return;
  64. }
  65. if (isTs) {
  66. // we expect ts-node to be available
  67. const tsNode = require('ts-node');
  68. if (!tsNode) {
  69. console.error(`For "populate" to work with TypeScript projects, you must have ts-node installed`);
  70. process.exit(1);
  71. return;
  72. }
  73. require('ts-node').register();
  74. }
  75. const index = require(configFile);
  76. if (!index) {
  77. console.error(`Could not read the contents of "${configFile}"`);
  78. process.exit(1);
  79. return;
  80. }
  81. if (!index.config) {
  82. console.error(`The file "${configFile}" does not export a "config" object`);
  83. process.exit(1);
  84. return;
  85. }
  86. const config = index.config;
  87. // Force the sync mode on, so that all the tables are created
  88. // on this initial run.
  89. config.dbConnectionOptions.synchronize = true;
  90. const { bootstrap } = require('@vendure/core');
  91. console.log('Bootstrapping Vendure server...');
  92. const app = await bootstrap(config);
  93. return app;
  94. }
  95. export async function populateInitialData(app: INestApplication, initialData: object) {
  96. const populator = app.get(Populator);
  97. try {
  98. await populator.populateInitialData(initialData);
  99. } catch (err) {
  100. console.error(err.message);
  101. }
  102. }
  103. export async function populateCollections(app: INestApplication, initialData: object) {
  104. const populator = app.get(Populator);
  105. try {
  106. await populator.populateCollections(initialData);
  107. } catch (err) {
  108. console.error(err.message);
  109. }
  110. }
  111. async function importProductsFromFile(app: INestApplication, csvPath: string, languageCode: string) {
  112. // import the csv of same product data
  113. const importer = app.get(Importer);
  114. const productData = await fs.readFile(csvPath, 'utf-8');
  115. const importResult = await importer.parseAndImport(productData, languageCode, true).toPromise();
  116. if (importResult.errors.length) {
  117. const errorFile = path.join(process.cwd(), 'vendure-import-error.log');
  118. console.log(
  119. `${importResult.errors.length} errors encountered when importing product data. See: ${errorFile}`,
  120. );
  121. await fs.writeFile(errorFile, importResult.errors.join('\n'));
  122. }
  123. logColored(`\nImported ${importResult.imported} products`);
  124. }