populate.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { INestApplication } from '@nestjs/common';
  2. import * as fs from 'fs-extra';
  3. import * as path from 'path';
  4. import { Connection } from 'typeorm';
  5. import { logColored } from './cli-utils';
  6. // tslint:disable:no-console
  7. export async function populate() {
  8. logColored('\nPopulating... (this may take a minute or two)\n');
  9. const app = await getApplicationRef();
  10. if (app) {
  11. const { Populator } = require('vendure');
  12. const populator = app.get(Populator);
  13. const initialData = require('./assets/initial-data.json');
  14. await populator.populateInitialData(initialData);
  15. logColored('Done!');
  16. await app.close();
  17. process.exit(0);
  18. }
  19. }
  20. async function getApplicationRef(): Promise<INestApplication | undefined> {
  21. const tsConfigFile = path.join(process.cwd(), 'vendure-config.ts');
  22. const jsConfigFile = path.join(process.cwd(), 'vendure-config.js');
  23. let isTs = false;
  24. let configFile: string | undefined;
  25. if (fs.existsSync(tsConfigFile)) {
  26. configFile = tsConfigFile;
  27. isTs = true;
  28. } else if (fs.existsSync(jsConfigFile)) {
  29. configFile = jsConfigFile;
  30. }
  31. if (!configFile) {
  32. console.error(`Could not find a config file`);
  33. console.error(`Checked "${tsConfigFile}", "${jsConfigFile}"`);
  34. process.exit(1);
  35. return;
  36. }
  37. if (isTs) {
  38. // we expect ts-node to be available
  39. const tsNode = require('ts-node');
  40. if (!tsNode) {
  41. console.error(`For "populate" to work with TypeScript projects, you must have ts-node installed`);
  42. process.exit(1);
  43. return;
  44. }
  45. require('ts-node').register();
  46. }
  47. const index = require(configFile);
  48. if (!index) {
  49. console.error(`Could not read the contents of "${configFile}"`);
  50. process.exit(1);
  51. return;
  52. }
  53. if (!index.config) {
  54. console.error(`The file "${configFile}" does not export a "config" object`);
  55. process.exit(1);
  56. return;
  57. }
  58. const config = index.config;
  59. const { bootstrap } = require('vendure');
  60. console.log('Bootstrapping Vendure server...');
  61. const app = await bootstrap(config);
  62. return app;
  63. }