graphql-schema-extensions.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { gql } from 'apollo-server-core';
  2. import { DocumentNode } from 'graphql';
  3. import { ElasticsearchOptions } from './options';
  4. export function generateSchemaExtensions(options: ElasticsearchOptions): DocumentNode {
  5. const customMappingTypes = generateCustomMappingTypes(options);
  6. return gql`
  7. extend type SearchResponse {
  8. prices: SearchResponsePriceData!
  9. }
  10. type SearchResponsePriceData {
  11. range: PriceRange!
  12. rangeWithTax: PriceRange!
  13. buckets: [PriceRangeBucket!]!
  14. bucketsWithTax: [PriceRangeBucket!]!
  15. }
  16. type PriceRangeBucket {
  17. to: Int!
  18. count: Int!
  19. }
  20. extend input SearchInput {
  21. priceRange: PriceRangeInput
  22. priceRangeWithTax: PriceRangeInput
  23. }
  24. input PriceRangeInput {
  25. min: Int!
  26. max: Int!
  27. }
  28. ${customMappingTypes ? customMappingTypes : ''}
  29. `;
  30. }
  31. function generateCustomMappingTypes(options: ElasticsearchOptions): DocumentNode | undefined {
  32. const productMappings = Object.entries(options.customProductMappings || {});
  33. const variantMappings = Object.entries(options.customProductVariantMappings || {});
  34. if (productMappings.length || variantMappings.length) {
  35. let sdl = ``;
  36. if (productMappings.length) {
  37. sdl += `
  38. type CustomProductMappings {
  39. ${productMappings.map(([name, def]) => `${name}: ${def.graphQlType}`)}
  40. }
  41. `;
  42. }
  43. if (variantMappings.length) {
  44. sdl += `
  45. type CustomProductVariantMappings {
  46. ${variantMappings.map(([name, def]) => `${name}: ${def.graphQlType}`)}
  47. }
  48. `;
  49. }
  50. if (productMappings.length && variantMappings.length) {
  51. sdl += `
  52. union CustomMappings = CustomProductMappings | CustomProductVariantMappings
  53. extend type SearchResult {
  54. customMappings: CustomMappings!
  55. }
  56. `;
  57. } else if (productMappings.length) {
  58. sdl += `
  59. extend type SearchResult {
  60. customMappings: CustomProductMappings!
  61. }
  62. `;
  63. } else if (variantMappings.length) {
  64. sdl += `
  65. extend type SearchResult {
  66. customMappings: CustomProductVariantMappings!
  67. }
  68. `;
  69. }
  70. return gql`
  71. ${sdl}
  72. `;
  73. }
  74. return;
  75. }