init-load-test.ts 11 KB

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