mock-data.service.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import faker from 'faker/locale/en_GB';
  2. import gql from 'graphql-tag';
  3. import { CreateAddressInput, CreateCustomerInput } from '../e2e/graphql/generated-e2e-admin-types';
  4. import { SimpleGraphQLClient } from './simple-graphql-client';
  5. // tslint:disable:no-console
  6. /**
  7. * A service for creating mock data via the GraphQL API.
  8. */
  9. export class MockDataService {
  10. apiUrl: string;
  11. constructor(private client: SimpleGraphQLClient, private logging = true) {
  12. // make the generated results deterministic
  13. faker.seed(1);
  14. }
  15. async populateCustomers(count: number = 5): Promise<any> {
  16. for (let i = 0; i < count; i++) {
  17. const firstName = faker.name.firstName();
  18. const lastName = faker.name.lastName();
  19. const query1 = gql`
  20. mutation CreateCustomer($input: CreateCustomerInput!, $password: String) {
  21. createCustomer(input: $input, password: $password) {
  22. id
  23. emailAddress
  24. }
  25. }
  26. `;
  27. const variables1 = {
  28. input: {
  29. firstName,
  30. lastName,
  31. emailAddress: faker.internet.email(firstName, lastName),
  32. phoneNumber: faker.phone.phoneNumber(),
  33. } as CreateCustomerInput,
  34. password: 'test',
  35. };
  36. const customer: { id: string; emailAddress: string } | void = await this.client
  37. .query(query1, variables1)
  38. .then((data: any) => data.createCustomer, err => this.log(err));
  39. if (customer) {
  40. const query2 = gql`
  41. mutation($customerId: ID!, $input: CreateAddressInput!) {
  42. createCustomerAddress(customerId: $customerId, input: $input) {
  43. id
  44. streetLine1
  45. }
  46. }
  47. `;
  48. const variables2 = {
  49. input: {
  50. fullName: `${firstName} ${lastName}`,
  51. streetLine1: faker.address.streetAddress(),
  52. city: faker.address.city(),
  53. province: faker.address.county(),
  54. postalCode: faker.address.zipCode(),
  55. countryCode: 'GB',
  56. } as CreateAddressInput,
  57. customerId: customer.id,
  58. };
  59. await this.client.query(query2, variables2).catch(err => this.log(err));
  60. }
  61. }
  62. this.log(`Created ${count} Customers`);
  63. }
  64. private log(...args: any[]) {
  65. if (this.logging) {
  66. console.log(...args);
  67. }
  68. }
  69. }