This repository was archived by the owner on Jan 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseGist.ts
128 lines (110 loc) · 2.79 KB
/
useGist.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
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
import { Ref, shallowRef } from '@vue/reactivity'
import { watch } from '@vue-reactivity/watch'
import { throttle } from 'throttle-debounce'
import YAML from 'js-yaml'
import Base64 from 'js-base64'
import { octokit } from './config'
import { Sentry } from './sentry'
export function useGit<T>(owner: string, repo: string, filepath: string, init: T) {
let writing = false
const r = shallowRef(init) as Ref<T> & { ready: () => Promise<void> }
async function fetch() {
const { data } = await octokit.repos.getContent({
owner,
repo,
path: filepath,
})
writing = true
r.value = JSON.parse(Base64.decode((data as any)?.content || '') || '{}')
writing = false
}
async function update(content: string) {
try {
return await octokit.repos.createOrUpdateFileContents({
owner,
repo,
path: filepath,
message: `chore: update "${filepath}"`,
content: Base64.encode(content),
committer: {
name: 'Knightly Bot',
email: '[email protected]',
},
author: {
name: 'Knightly Bot',
email: '[email protected]',
},
})
}
catch (e) {
Sentry.captureException(e)
throw e
}
}
const throttledUpdate = throttle(10 * 1000, update)
watch(
r,
(v) => {
if (writing)
return
throttledUpdate(JSON.stringify(v, null, 2))
},
{ deep: true },
)
const _p = fetch()
.catch((e) => {
console.error(e)
process.exit(1)
})
Object.defineProperty(r, 'ready', { value: () => _p })
return r
}
export function useGist<T>(id: string, filename: string, init: T) {
let writing = false
const isYAML = filename.match(/\.ya?ml$/i)
const r = shallowRef(init) as unknown as Ref<T> & { ready: () => Promise<void> }
async function fetch() {
const { data: gist } = await octokit.gists.get({ gist_id: id })
writing = true
r.value = isYAML
? YAML.load(gist.files?.[filename]?.content || '{}') as unknown as T
: JSON.parse(gist.files?.[filename]?.content || '{}')
writing = false
}
async function update(v: any) {
try {
await octokit.gists.update({
gist_id: id,
files: {
[filename]: {
filename,
content: isYAML
? YAML.dump(v)
: JSON.stringify(v, null, 2),
},
},
})
}
catch (e) {
Sentry.captureException(e)
throw e
}
}
const throttledUpdate = throttle(10 * 1000, update)
watch(
r,
(v) => {
if (writing)
return
throttledUpdate(v)
},
{ deep: true },
)
const _p = fetch()
.catch((e) => {
console.error(e)
process.exit(1)
})
Object.defineProperty(r, 'ready', { value: () => _p })
return r
}