-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithubJsonRepository.ts
More file actions
69 lines (64 loc) · 2.07 KB
/
Copy pathgithubJsonRepository.ts
File metadata and controls
69 lines (64 loc) · 2.07 KB
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 type { GithubFilePayload } from '../githubContents'
import type { JsonStorageReadResult, JsonStorageRepository, JsonStorageWriteInput } from './types'
import { Buffer } from 'node:buffer'
import { getGithubJsonFile, putGithubJsonFile } from '../githubContents'
export interface GithubJsonRepositoryOptions {
token: string
owner: string
repo: string
path: string
ref?: string
/** When the path has no file yet (404), `read` returns this as `parsed` and revision `'0'` (same as local). */
defaultIfMissing: unknown
/** Throw 413 when read or written content exceeds this many bytes. */
maxBytes?: number
/** Emit a console.warn once when content exceeds this many bytes (soft limit). */
warnAtBytes?: number
}
export class GithubJsonRepository implements JsonStorageRepository {
readonly adapterKind = 'github' as const
constructor(private readonly opts: GithubJsonRepositoryOptions) {}
async read(): Promise<JsonStorageReadResult> {
try {
const { parsed, sha } = await getGithubJsonFile(
this.opts.token,
this.opts.owner,
this.opts.repo,
this.opts.path,
this.opts.ref,
{ maxBytes: this.opts.maxBytes, warnAtBytes: this.opts.warnAtBytes },
)
return { parsed, revision: sha }
}
catch (e: any) {
if (e?.statusCode === 404) {
return {
parsed: structuredClone(this.opts.defaultIfMissing),
revision: '0',
}
}
throw e
}
}
async write(input: JsonStorageWriteInput): Promise<void> {
const content = Buffer.from(input.bodyUtf8, 'utf8').toString('base64')
const payload: GithubFilePayload = {
message: input.message || 'Update JSON',
content,
}
if (this.opts.ref) {
payload.branch = this.opts.ref
}
if (input.revision && input.revision !== '0') {
payload.sha = input.revision
}
await putGithubJsonFile(
this.opts.token,
this.opts.owner,
this.opts.repo,
this.opts.path,
payload,
{ maxBytes: this.opts.maxBytes, warnAtBytes: this.opts.warnAtBytes },
)
}
}