-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathschema.js
137 lines (121 loc) · 2.74 KB
/
schema.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
const immutable = require('immutable')
const graphqlTools = require('graphql-tools')
const {request_bus, response_bus} = require('./message_bus')
const Mpn = `{
manufacturer : String!
part : String!
}`
const Sku = `{
vendor : String!
part : String!
}`
const schema = `
type Mpn ${Mpn}
input MpnInput ${Mpn}
type Sku ${Sku}
input SkuInput ${Sku}
input MpnOrSku {mpn: MpnInput, sku: SkuInput}
type Query {
part(mpn: MpnInput, sku: SkuInput): Part
match(parts: [MpnOrSku]!) : [Part]!
search(term: String!): [Part]!
}
type Part {
mpn : Mpn
image : Image
datasheet : String
description : String
offers : [Offer]
specs : [Spec]
type : String
}
type Offer {
sku : Sku
prices : Prices
image : Image
description : String
specs : [Spec]
in_stock_quantity : Int
stock_location : String
moq : Int
}
type Prices {
USD: [[Float]]
EUR: [[Float]]
GBP: [[Float]]
SGD: [[Float]]
}
type Image {
url : String
credit_string : String
credit_url : String
}
type Spec {
key : String
name : String
value : String
}
`
const resolverMap = {
Query: {
part(_, {mpn, sku}) {
return runPart({mpn, sku})
},
match(_, {parts}) {
return Promise.all(parts.map(runPart))
},
search(_, {term}) {
if (!term) {
return []
}
return run({term})
},
},
}
function runPart({mpn, sku}) {
console.info(
`got request for ${(mpn && JSON.stringify(mpn)) ||
(sku && JSON.stringify(sku))}`
)
if (!(mpn || sku)) {
return Promise.reject(Error('Mpn or Sku required'))
}
if (sku && sku.vendor !== 'Digikey') {
sku.part = sku.part.replace(/-/g, '')
}
return run({mpn, sku})
}
function makeId() {
this.id = this.id || 1
return this.id++
}
function run(query) {
const id = makeId()
query.id = id
query = immutable.fromJS(query)
const time_stamped = immutable.Map({
query,
time: Date.now(),
})
return new Promise((resolve, reject) => {
response_bus.once(id, r => {
if (query.get('term')) {
r = r.filter(x => x).filter(x => x.get('mpn'))
} else if (!r.get('mpn')) {
return resolve()
}
console.info(
`request for ${query.get('term') ||
query.getIn(['mpn', 'part']) ||
query.getIn(['sku', 'part'])} took ${Date.now() -
time_stamped.get('time')} ms`
)
resolve(r.toJS())
})
request_bus.emit('request', time_stamped)
})
}
module.exports = graphqlTools.makeExecutableSchema({
typeDefs: schema,
resolvers: resolverMap,
})