mock-data.service.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. id
  22. emailAddress
  23. }
  24. }
  25. `;
  26. const variables1 = {
  27. input: {
  28. firstName,
  29. lastName,
  30. emailAddress: faker.internet.email(firstName, lastName),
  31. phoneNumber: faker.phone.phoneNumber(),
  32. },
  33. password: 'test',
  34. };
  35. const customer: { id: string; emailAddress: string } | void = await this.client
  36. .query(query1, variables1)
  37. .then((data: any) => data.createCustomer, err => this.log(err));
  38. if (customer) {
  39. const query2 = gql`
  40. mutation($customerId: ID!, $input: CreateAddressInput!) {
  41. createCustomerAddress(customerId: $customerId, input: $input) {
  42. id
  43. streetLine1
  44. }
  45. }
  46. `;
  47. const variables2 = {
  48. input: {
  49. fullName: `${firstName} ${lastName}`,
  50. streetLine1: faker.address.streetAddress(),
  51. city: faker.address.city(),
  52. province: faker.address.county(),
  53. postalCode: faker.address.zipCode(),
  54. countryCode: 'GB',
  55. },
  56. customerId: customer.id,
  57. };
  58. await this.client.query(query2, variables2).catch(err => this.log(err));
  59. }
  60. }
  61. this.log(`Created ${count} Customers`);
  62. }
  63. private log(...args: any[]) {
  64. if (this.logging) {
  65. console.log(...args);
  66. }
  67. }
  68. }