-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhoogle.ts
88 lines (75 loc) · 2.18 KB
/
hoogle.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
86
87
88
import { Schema, validate } from 'https://deno.land/x/[email protected]/mod.ts'
import outdent from 'http://deno.land/x/[email protected]/mod.ts'
import { useEnvVar } from './useEnvVar.ts'
interface SearchOptions {
start?: string
count?: string
}
export type SearchResult = Array<{
url: string
module: {
name?: string
url?: string
}
package: {
name?: string
url?: string
}
item: string
docs: string
}> // useless 'type' field is ignored
const searchResultSchema = {
elements: {
properties: {
url: { type: 'string '},
module: {
optionalProperties: {
name: { type: 'string '},
url: { type: 'string' }
}
},
package: {
optionalProperties: {
name: { type: 'string '},
url: { type: 'string' }
}
},
item: { type: 'string' },
docs: { type: 'string '},
type: { type: 'string' } // I don't know why this field is present in API, but it exists
}
}
} as Schema
const HOOGLE = useEnvVar('HOOGLE', 'Hoogle domain name')
export async function search(query: string, options: SearchOptions = {}): Promise<SearchResult> {
const completedOptions = { start: '1', count: '1', ...options }
const queryParams = new URLSearchParams({
mode: 'json',
format: 'text',
hoogle: query,
...completedOptions
})
const apiResponse = await (await fetch(`https://${HOOGLE}?${queryParams}`)).text()
const apiJSONResponse = JSON.parse(apiResponse)
const schemaViolations = validate(searchResultSchema, apiJSONResponse)
if (schemaViolations.length > 0) {
const formattedViolations = schemaViolations.map(
({ instancePath, schemaPath }) => outdent`
'apiJSONResponse.${instancePath.join('.')}' violates schema '${schemaPath.join('.')}'
`
).join('\n')
const errorMessage = outdent`
Hoogle's response for query '${query}' failed to pass json validation.
got:
${apiResponse}
violations:
${formattedViolations}
`
throw new Error(errorMessage)
}
console.info(outdent`
querying '${query}' succeed with response:
${apiResponse}
`)
return apiJSONResponse as SearchResult
}