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