-
Notifications
You must be signed in to change notification settings - Fork 6
/
example.ts
81 lines (69 loc) · 2.08 KB
/
example.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
import {groqStore, Subscription} from '../src/browser'
//
;(function () {
// Yep
const queryEl = document.getElementById('query') as HTMLTextAreaElement
const resultEl = document.getElementById('result') as HTMLTextAreaElement
const clearBtnEl = document.getElementById('clear') as HTMLButtonElement
const executeBtnEl = document.getElementById('execute') as HTMLButtonElement
const subscribeBtnEl = document.getElementById('subscribe') as HTMLButtonElement
attach()
populate()
let subscription: Subscription | null | undefined
const dataset = groqStore({
projectId: 'groqstore',
dataset: 'fixture',
listen: true,
overlayDrafts: true,
})
function attach() {
clearBtnEl.addEventListener('click', clear, false)
executeBtnEl.addEventListener('click', execute, false)
subscribeBtnEl.addEventListener('click', subscribe, false)
queryEl.addEventListener('keyup', onKeyUp, false)
}
function populate() {
if (!localStorage.groqStore) {
return
}
queryEl.value = localStorage.groqStore
}
async function execute() {
resultEl.value = '… querying …'
localStorage.setItem('groqStore', queryEl.value)
try {
onResult(await dataset.query(queryEl.value))
} catch (err: any) {
onError(err.message || 'Unknown error')
}
}
function subscribe() {
if (subscription) {
subscription.unsubscribe()
subscription = null
subscribeBtnEl.textContent = 'Subscribe'
executeBtnEl.disabled = false
clear()
} else {
resultEl.value = '… querying …'
executeBtnEl.disabled = true
subscribeBtnEl.textContent = 'Unsubscribe'
subscription = dataset.subscribe(queryEl.value, {}, onResult)
}
}
function onResult(queryResult: any) {
const json = JSON.stringify(queryResult, null, 2)
resultEl.value = json
}
function onError(msg: string) {
resultEl.value = `/*** ERROR ***/\n\n${msg}`
}
function onKeyUp(evt: KeyboardEvent) {
if (evt.ctrlKey && evt.key === 'Enter') {
execute()
}
}
function clear() {
resultEl.value = ''
}
})()