forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
82 lines (73 loc) · 2.29 KB
/
Copy pathapi.ts
File metadata and controls
82 lines (73 loc) · 2.29 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
70
71
72
73
74
75
76
77
78
79
80
81
82
import { getBasepath } from "hookrouter"
import {
Application,
ApplicationsResponse,
CreateSessionResponse,
FilesResponse,
LoginResponse,
RecentResponse,
} from "../common/api"
import { ApiEndpoint, HttpCode, HttpError } from "../common/http"
export interface AuthBody {
password: string
}
/**
* Set authenticated status.
*/
export function setAuthed(authed: boolean): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(window as any).setAuthed(authed)
}
/**
* Try making a request. Throw an error if the request is anything except OK.
* Also set authed to false if the request returns unauthorized.
*/
const tryRequest = async (endpoint: string, options?: RequestInit): Promise<Response> => {
const response = await fetch(getBasepath() + "/api" + endpoint + "/", options)
if (response.status === HttpCode.Unauthorized) {
setAuthed(false)
}
if (response.status !== HttpCode.Ok) {
const text = await response.text()
throw new HttpError(text || response.statusText || "unknown error", response.status)
}
return response
}
/**
* Try authenticating.
*/
export const authenticate = async (body?: AuthBody): Promise<LoginResponse> => {
const response = await tryRequest(ApiEndpoint.login, {
method: "POST",
body: JSON.stringify({ ...body, basePath: getBasepath() }),
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
},
})
return response.json()
}
export const getFiles = async (): Promise<FilesResponse> => {
const response = await tryRequest(ApiEndpoint.files)
return response.json()
}
export const getRecent = async (): Promise<RecentResponse> => {
const response = await tryRequest(ApiEndpoint.recent)
return response.json()
}
export const getApplications = async (): Promise<ApplicationsResponse> => {
const response = await tryRequest(ApiEndpoint.applications)
return response.json()
}
export const getSession = async (app: Application): Promise<CreateSessionResponse> => {
const response = await tryRequest(ApiEndpoint.session, {
method: "POST",
body: JSON.stringify(app),
})
return response.json()
}
export const killSession = async (app: Application): Promise<Response> => {
return tryRequest(ApiEndpoint.session, {
method: "DELETE",
body: JSON.stringify(app),
})
}