-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (61 loc) · 1.65 KB
/
index.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
import { fetchSetDefaults, fetchReadableStream } from '@datastream/fetch'
const domain = 'https://api.datastream.org'
export const setAPIKey = (apikey) => {
fetchSetDefaults({
headers: {
Accept: 'application/vnd.api+json',
'x-api-key': apikey
},
qs: {},
dataPath: 'value',
rateLimit: 0.5
})
}
export const request = async (path, qs) => {
const options = {
url: `${domain}${path}`,
qs
}
return fetchReadableStream(options)
}
export const metadata = async (qs) => {
qs.$top ??= 100
return request('/v1/odata/v4/Metadata', qs)
}
export const locations = async (qs) => {
qs.$top ??= 10000
return request('/v1/odata/v4/Locations', qs)
}
const matchPartitionedRegExp = /(^Id| Id|^LocationId| LocationId)/
const partitionRequest = async (path, qs) => {
// If filtering by specific Id or LocationId, no need to partition
if (matchPartitionedRegExp.test(qs.$filter ?? '')) {
return request(path, qs)
}
const locationStream = await locations({
$select: 'Id',
$filter: qs.$filter.replaceAll('LocationId', 'Id')
})
const optionsArray = []
for await (const location of locationStream) {
const options = {
url: `${domain}${path}`,
qs: {
...qs,
$filter: `LocationId eq ${location.Id}${
qs.$filter && ` and ${qs.$filter}`
}`
}
}
optionsArray.push(options)
}
return fetchReadableStream(optionsArray)
}
export const observations = async (qs) => {
qs.$top ??= 10000
return partitionRequest('/v1/odata/v4/Observations', qs)
}
export const records = async (qs) => {
qs.$top ??= 10000
return partitionRequest('/v1/odata/v4/Records', qs)
}