init-load-test.ts 11 KB

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