init-load-test.ts 11 KB

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