mock-data.service.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import * as faker from 'faker/locale/en_GB';
  2. import gql from 'graphql-tag';
  3. import {
  4. CreateFacet,
  5. CreateFacetValueWithFacetInput,
  6. CreateFacetVariables,
  7. CreateProduct,
  8. CreateProductOptionGroup,
  9. CreateProductOptionGroupVariables,
  10. CreateProductVariables,
  11. GenerateProductVariants,
  12. GenerateProductVariantsVariables,
  13. LanguageCode,
  14. ProductTranslationInput,
  15. UpdateProductVariants,
  16. UpdateProductVariantsVariables,
  17. } from 'shared/generated-types';
  18. import { CREATE_FACET } from '../../admin-ui/src/app/data/mutations/facet-mutations';
  19. import {
  20. CREATE_PRODUCT,
  21. CREATE_PRODUCT_OPTION_GROUP,
  22. GENERATE_PRODUCT_VARIANTS,
  23. UPDATE_PRODUCT_VARIANTS,
  24. } from '../../admin-ui/src/app/data/mutations/product-mutations';
  25. import { CreateAddressDto } from '../src/entity/address/address.dto';
  26. import { CreateAdministratorDto } from '../src/entity/administrator/administrator.dto';
  27. import { Channel } from '../src/entity/channel/channel.entity';
  28. import { CreateCustomerDto } from '../src/entity/customer/customer.dto';
  29. import { Customer } from '../src/entity/customer/customer.entity';
  30. import { GraphQlClient } from './simple-graphql-client';
  31. // tslint:disable:no-console
  32. /**
  33. * A service for creating mock data via the GraphQL API.
  34. */
  35. export class MockDataService {
  36. apiUrl: string;
  37. constructor(private client: GraphQlClient, private logging = true) {
  38. // make the generated results deterministic
  39. faker.seed(1);
  40. }
  41. async populateChannels(channelCodes: string[]): Promise<Channel[]> {
  42. const channels: Channel[] = [];
  43. for (const code of channelCodes) {
  44. const channel = await this.client.query<any>(gql`
  45. mutation {
  46. createChannel(code: "${code}") {
  47. id
  48. code
  49. token
  50. }
  51. }
  52. `);
  53. channels.push(channel.createChannel);
  54. this.log(`Created Channel: ${channel.createChannel.code}`);
  55. }
  56. return channels;
  57. }
  58. async populateOptions(): Promise<any> {
  59. await this.client
  60. .query<CreateProductOptionGroup, CreateProductOptionGroupVariables>(CREATE_PRODUCT_OPTION_GROUP, {
  61. input: {
  62. code: 'size',
  63. translations: [
  64. { languageCode: LanguageCode.en, name: 'Size' },
  65. { languageCode: LanguageCode.de, name: 'Größe' },
  66. ],
  67. options: [
  68. {
  69. code: 'small',
  70. translations: [
  71. { languageCode: LanguageCode.en, name: 'Small' },
  72. { languageCode: LanguageCode.de, name: 'Klein' },
  73. ],
  74. },
  75. {
  76. code: 'large',
  77. translations: [
  78. { languageCode: LanguageCode.en, name: 'Large' },
  79. { languageCode: LanguageCode.de, name: 'Groß' },
  80. ],
  81. },
  82. ],
  83. },
  84. })
  85. .then(
  86. data => this.log('Created option group:', data.createProductOptionGroup.name),
  87. err => this.log(err),
  88. );
  89. }
  90. async populateAdmins(): Promise<any> {
  91. const query = gql`
  92. mutation($input: CreateAdministratorInput!) {
  93. createAdministrator(input: $input) {
  94. id
  95. emailAddress
  96. }
  97. }
  98. `;
  99. const variables = {
  100. input: {
  101. firstName: 'Super',
  102. lastName: 'Admin',
  103. emailAddress: 'admin@test.com',
  104. password: 'test',
  105. } as CreateAdministratorDto,
  106. };
  107. await this.client
  108. .query(query, variables)
  109. .then(data => this.log('Created Administrator:', data), err => this.log(err));
  110. }
  111. async populateCustomers(count: number = 5): Promise<any> {
  112. for (let i = 0; i < count; i++) {
  113. const firstName = faker.name.firstName();
  114. const lastName = faker.name.lastName();
  115. const query1 = gql`
  116. mutation CreateCustomer($input: CreateCustomerInput!, $password: String) {
  117. createCustomer(input: $input, password: $password) {
  118. id
  119. emailAddress
  120. }
  121. }
  122. `;
  123. const variables1 = {
  124. input: {
  125. firstName,
  126. lastName,
  127. emailAddress: faker.internet.email(firstName, lastName),
  128. phoneNumber: faker.phone.phoneNumber(),
  129. } as CreateCustomerDto,
  130. password: 'test',
  131. };
  132. const customer: Customer | void = await this.client
  133. .query(query1, variables1)
  134. .then((data: any) => data.createCustomer as Customer, err => this.log(err));
  135. if (customer) {
  136. const query2 = gql`
  137. mutation($customerId: ID!, $input: CreateAddressInput) {
  138. createCustomerAddress(customerId: $customerId, input: $input) {
  139. id
  140. streetLine1
  141. }
  142. }
  143. `;
  144. const variables2 = {
  145. input: {
  146. fullName: `${firstName} ${lastName}`,
  147. streetLine1: faker.address.streetAddress(),
  148. city: faker.address.city(),
  149. province: faker.address.county(),
  150. postalCode: faker.address.zipCode(),
  151. country: faker.address.country(),
  152. } as CreateAddressDto,
  153. customerId: customer.id,
  154. };
  155. await this.client.query(query2, variables2).then(
  156. data => {
  157. this.log(`Created Customer ${i + 1}:`, data);
  158. return data as Customer;
  159. },
  160. err => this.log(err),
  161. );
  162. }
  163. }
  164. }
  165. async populateProducts(count: number = 5): Promise<any> {
  166. for (let i = 0; i < count; i++) {
  167. const query = CREATE_PRODUCT;
  168. const name = faker.commerce.productName();
  169. const slug = name.toLowerCase().replace(/\s+/g, '-');
  170. const description = faker.lorem.sentence();
  171. const languageCodes = [LanguageCode.en, LanguageCode.de];
  172. const variables = {
  173. input: {
  174. image: faker.image.imageUrl(),
  175. optionGroupCodes: ['size'],
  176. translations: languageCodes.map(code =>
  177. this.makeProductTranslation(code, name, slug, description),
  178. ),
  179. },
  180. };
  181. const product = await this.client
  182. .query<CreateProduct, CreateProductVariables>(query, variables)
  183. .then(
  184. data => {
  185. this.log(`Created Product ${i + 1}:`, data.createProduct.name);
  186. return data;
  187. },
  188. err => this.log(err),
  189. );
  190. if (product) {
  191. const prodWithVariants = await this.makeProductVariant(product.createProduct.id);
  192. const variants = prodWithVariants.generateVariantsForProduct.variants;
  193. for (const variant of variants) {
  194. const variantEN = variant.translations[0];
  195. const variantDE = { ...variantEN };
  196. variantDE.languageCode = LanguageCode.de;
  197. variantDE.name = variantDE.name.replace(LanguageCode.en, LanguageCode.de);
  198. delete variantDE.id;
  199. variant.translations.push(variantDE);
  200. }
  201. await this.client.query<UpdateProductVariants, UpdateProductVariantsVariables>(
  202. UPDATE_PRODUCT_VARIANTS,
  203. {
  204. input: variants.map(({ id, translations, sku, price }) => ({
  205. id,
  206. translations,
  207. sku,
  208. price,
  209. })),
  210. },
  211. );
  212. }
  213. }
  214. }
  215. async populateFacets() {
  216. await this.client.query<CreateFacet, CreateFacetVariables>(CREATE_FACET, {
  217. input: {
  218. code: 'brand',
  219. translations: [
  220. {
  221. languageCode: LanguageCode.en,
  222. name: 'Brand',
  223. },
  224. {
  225. languageCode: LanguageCode.en,
  226. name: 'Marke',
  227. },
  228. ],
  229. values: this.makeFacetValues(10),
  230. },
  231. });
  232. this.log('Created "brand" Facet');
  233. }
  234. private makeFacetValues(count: number): CreateFacetValueWithFacetInput[] {
  235. return Array.from({ length: count }).map(() => {
  236. const brand = faker.company.companyName();
  237. return {
  238. code: brand.replace(/\s/g, '_'),
  239. translations: [
  240. {
  241. languageCode: LanguageCode.en,
  242. name: brand,
  243. },
  244. {
  245. languageCode: LanguageCode.de,
  246. name: brand,
  247. },
  248. ],
  249. };
  250. });
  251. }
  252. private makeProductTranslation(
  253. languageCode: LanguageCode,
  254. name: string,
  255. slug: string,
  256. description: string,
  257. ): ProductTranslationInput {
  258. return {
  259. languageCode,
  260. name: `${languageCode} ${name}`,
  261. slug: `${languageCode} ${slug}`,
  262. description: `${languageCode} ${description}`,
  263. };
  264. }
  265. private async makeProductVariant(productId: string): Promise<GenerateProductVariants> {
  266. const query = GENERATE_PRODUCT_VARIANTS;
  267. return this.client.query<GenerateProductVariants, GenerateProductVariantsVariables>(query, {
  268. productId,
  269. defaultSku: faker.random.alphaNumeric(5),
  270. defaultPrice: faker.random.number({
  271. min: 100,
  272. max: 1000,
  273. }),
  274. });
  275. }
  276. private log(...args: any[]) {
  277. if (this.logging) {
  278. console.log(...args);
  279. }
  280. }
  281. }