1
0

mock-data.service.ts 2.7 KB

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