init-load-test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. // tslint:disable-next-line:no-reference
  2. /// <reference path="../../core/typings.d.ts" />
  3. import { bootstrap, VendureConfig } from '@vendure/core';
  4. import { populate } from '@vendure/core/cli/populate';
  5. import { BaseProductRecord } from '@vendure/core/dist/data-import/providers/import-parser/import-parser';
  6. import stringify from 'csv-stringify';
  7. import fs from 'fs';
  8. import path from 'path';
  9. import { clearAllTables } from '../../core/mock-data/clear-all-tables';
  10. import { initialData } from '../../core/mock-data/data-sources/initial-data';
  11. import { populateCustomers } from '../../core/mock-data/populate-customers';
  12. import { devConfig } from '../dev-config';
  13. import { getLoadTestConfig, getMysqlConnectionOptions, getProductCount, getProductCsvFilePath } from './load-test-config';
  14. // tslint:disable:no-console
  15. /**
  16. * A script used to populate a database with test data for load testing.
  17. */
  18. if (require.main === module) {
  19. // Running from command line
  20. isDatabasePopulated()
  21. .then(isPopulated => {
  22. if (!isPopulated) {
  23. const count = getProductCount();
  24. const config = getLoadTestConfig('bearer');
  25. const csvFile = getProductCsvFilePath();
  26. return clearAllTables(config.dbConnectionOptions, true)
  27. .then(() => {
  28. if (!fs.existsSync(csvFile)) {
  29. return generateProductsCsv(count);
  30. }
  31. })
  32. .then(() => populate(() => bootstrap(config),
  33. path.join(__dirname, '../../create/assets/initial-data.json'),
  34. csvFile,
  35. path.join(__dirname, './data-sources'),
  36. ))
  37. .then(async app => {
  38. console.log('populating customers...');
  39. await populateCustomers(10, config as any, true);
  40. return app.close();
  41. });
  42. } else {
  43. console.log('Database is already populated!');
  44. }
  45. })
  46. .then(
  47. () => process.exit(0),
  48. err => {
  49. console.log(err);
  50. process.exit(1);
  51. },
  52. );
  53. }
  54. /**
  55. * Tests to see whether the load test database is already populated.
  56. */
  57. function isDatabasePopulated(): Promise<boolean> {
  58. const mysql = require('mysql');
  59. const count = getProductCount();
  60. const mysqlConnectionOptions = getMysqlConnectionOptions(count);
  61. const connection = mysql.createConnection({
  62. host: mysqlConnectionOptions.host,
  63. user: mysqlConnectionOptions.username,
  64. password: mysqlConnectionOptions.password,
  65. database: mysqlConnectionOptions.database,
  66. });
  67. return new Promise<boolean>((resolve, reject) => {
  68. connection.connect((error: any) => {
  69. if (error) {
  70. reject(error);
  71. return;
  72. }
  73. connection.query('SELECT COUNT(id) as prodCount FROM product', (err: any, results: any) => {
  74. if (err) {
  75. if (err.code === 'ER_NO_SUCH_TABLE') {
  76. resolve(false);
  77. return;
  78. }
  79. reject(err);
  80. return;
  81. }
  82. resolve(results[0].prodCount === count);
  83. });
  84. });
  85. });
  86. }
  87. /**
  88. * Generates a CSV file of test product data which can then be imported into Vendure.
  89. */
  90. function generateProductsCsv(productCount: number = 100): Promise<void> {
  91. const result: BaseProductRecord[] = [];
  92. const stringifier = stringify({
  93. delimiter: ',',
  94. });
  95. const data: string[] = [];
  96. console.log(`Generating ${productCount} rows of test product data...`);
  97. stringifier.on('readable', () => {
  98. let row;
  99. // tslint:disable-next-line:no-conditional-assignment
  100. while (row = stringifier.read()) {
  101. data.push(row);
  102. }
  103. });
  104. return new Promise((resolve, reject) => {
  105. const csvFile = getProductCsvFilePath();
  106. stringifier.on('error', (err: any) => {
  107. reject(err.message);
  108. });
  109. stringifier.on('finish', async () => {
  110. fs.writeFileSync(csvFile, data.join(''));
  111. console.log(`Done! Saved to ${csvFile}`);
  112. resolve();
  113. });
  114. generateMockData(productCount, row => stringifier.write(row));
  115. stringifier.end();
  116. });
  117. }
  118. function generateMockData(productCount: number, writeFn: (row: string[]) => void) {
  119. const headers: Array<keyof BaseProductRecord> = [
  120. 'name',
  121. 'slug',
  122. 'description',
  123. 'assets',
  124. 'facets',
  125. 'optionGroups',
  126. 'optionValues',
  127. 'sku',
  128. 'price',
  129. 'taxCategory',
  130. 'variantAssets',
  131. 'variantFacets',
  132. ];
  133. writeFn(headers);
  134. const categories = getCategoryNames();
  135. for (let i = 1; i <= productCount; i++) {
  136. const outputRow: BaseProductRecord = {
  137. name: `Product ${i}`,
  138. slug: `product-${i}`,
  139. description: generateProductDescription(),
  140. assets: 'product-image.jpg',
  141. facets: `category:${categories[i % categories.length]}`,
  142. optionGroups: '',
  143. optionValues: '',
  144. sku: `PRODID${i}`,
  145. price: (Math.random() * 1000).toFixed(2),
  146. taxCategory: 'standard',
  147. variantAssets: '',
  148. variantFacets: '',
  149. };
  150. writeFn(Object.values(outputRow) as string[]);
  151. }
  152. }
  153. function getCategoryNames() {
  154. const allNames = initialData.collections.reduce((all, c) => [...all, ...c.facetNames], [] as string[]);
  155. return Array.from(new Set(allNames));
  156. }
  157. const parts = [
  158. `Now equipped with seventh-generation Intel Core processors`,
  159. `Laptop is snappier than ever`,
  160. `From daily tasks like launching apps and opening files to more advanced computing`,
  161. `You can power through your day thanks to faster SSDs and Turbo Boost processing up to 3.6GHz`,
  162. `Discover a truly immersive viewing experience with this monitor curved more deeply than any other`,
  163. `Wrapping around your field of vision the 1,800 R screencreates a wider field of view`,
  164. `This pc is optimised for gaming, and is also VR ready`,
  165. `The Intel Core-i7 CPU and High Performance GPU give the computer the raw power it needs to function at a high level`,
  166. `Boost your PC storage with this internal hard drive, designed just for desktop and all-in-one PCs`,
  167. `Let all your colleagues know that you are typing on this exclusive, colorful klicky-klacky keyboard`,
  168. `Solid conductors eliminate strand-interaction distortion and reduce jitter`,
  169. `As the surface is made of high-purity silver`,
  170. `the performance is very close to that of a solid silver cable`,
  171. `but priced much closer to solid copper cable`,
  172. `With its nostalgic design and simple point-and-shoot functionality`,
  173. `the Instant Camera is the perfect pick to get started with instant photography`,
  174. `This lens is a Di type lens using an optical system with improved multi-coating designed to function with digital SLR cameras as well as film cameras`,
  175. `Capture vivid, professional-style photographs with help from this lightweight tripod`,
  176. `The adjustable-height tripod makes it easy to achieve reliable stability`,
  177. `Just the right angle when going after that award-winning shot`,
  178. `Featuring a full carbon chassis - complete with cyclocross-specific carbon fork`,
  179. `It's got the low weight, exceptional efficiency and brilliant handling`,
  180. `You'll need to stay at the front of the pack`,
  181. `When you're working out you need a quality rope that doesn't tangle at every couple of jumps`,
  182. `Training gloves designed for optimum training`,
  183. `Our gloves promote proper punching technique because they are conformed to the natural shape of your fist`,
  184. `Dense, innovative two-layer foam provides better shock absorbency`,
  185. `Full padding on the front, back and wrist to promote proper punching technique`,
  186. `With tons of space inside (for max. 4 persons), full head height throughout`,
  187. `This tent offers you everything you need`,
  188. `Based on the 1970s iconic shape, but made to a larger 69cm size`,
  189. `These skateboards are great for beginners to learn the foot spacing required`,
  190. `Perfect for all-day cruising`,
  191. `This football features high-contrast graphics for high-visibility during play`,
  192. `Its machine-stitched tpu casing offers consistent performance`,
  193. `With its ultra-light, uber-responsive magic foam`,
  194. `The Running Shoe is ready to push you to victories both large and small`,
  195. `A spiky yet elegant house cactus`,
  196. `Perfect for the home or office`,
  197. `Origin and habitat: Probably native only to the Andes of Peru`,
  198. `Gloriously elegant`,
  199. `It can go along with any interior as it is a neutral color and the most popular Phalaenopsis overall`,
  200. `2 to 3 foot stems host large white flowers that can last for over 2 months`,
  201. `Excellent semi-evergreen bonsai`,
  202. `Indoors or out but needs some winter protection`,
  203. `All trees sent will leave the nursery in excellent condition and will be of equal quality or better than the photograph shown`,
  204. `Placing it at home or office can bring you fortune and prosperity`,
  205. `Guards your house and ward off ill fortune`,
  206. `Hand trowel for garden cultivating hammer finish epoxy-coated head`,
  207. `For improved resistance to rust, scratches, humidity and alkalines in the soil`,
  208. `A charming vintage white wooden chair`,
  209. `Featuring an extremely spherical pink balloon`,
  210. `The balloon may be detached and used for other purposes`,
  211. `This premium, tan-brown bonded leather seat is part of the 'chill' sofa range`,
  212. `The lever activated recline feature makes it easy to adjust to any position`,
  213. `This smart, bustle back design with rounded tight padded arms has been designed with your comfort in mind`,
  214. `This well-padded chair has foam pocket sprung seat cushions and fibre-filled back cushions`,
  215. `Modern tapered white polycotton pendant shade with a metallic silver chrome interior`,
  216. `For maximum light reflection`,
  217. `Reversible gimble so it can be used as a ceiling shade or as a lamp shade`,
  218. ];
  219. function generateProductDescription(): string {
  220. const take = Math.ceil(Math.random() * 4);
  221. return shuffle(parts).slice(0, take)
  222. .join('. ');
  223. }
  224. /**
  225. * Returns new copy of array in random order.
  226. * https://stackoverflow.com/a/6274381/772859
  227. */
  228. function shuffle<T>(arr: T[]): T[] {
  229. const a = arr.slice();
  230. for (let i = a.length - 1; i > 0; i--) {
  231. const j = Math.floor(Math.random() * (i + 1));
  232. [a[i], a[j]] = [a[j], a[i]];
  233. }
  234. return a;
  235. }