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
import { fetch } from "https://esm.town/v/std/fetch?v=4";
export type Profile = { s; id: string; bio: string; username: string; profileImageUrl: string };
export type Val = {
id: string;
author: {
id: string;
username: string;
};
name: string;
code: string;
public: boolean;
privacy: "public" | "private";
version: number;
runEndAt: string;
runStartAt: string;
logs: any[];
output: object;
error: object | null;
readme: string | null;
likeCount: number;
referenceCount: number;
};
export type ExpressionResult = string | number | Record<string, any> | any[] | boolean;
export class ValTownClient {
private baseURL: string;
private authenticated: boolean;
private authorization: string | undefined;
public alias: AliasEndpoint;
public eval: EvalEndpoint;
public me: MeEndpoint;
public users: UsersEndpoint;
public vals: ValsEndpoint;
public run: RunEndpoint;
public endpoint: Endpoint;
constructor({
baseURL = "https://api.val.town/v1",
authenticated = false,
}: {
baseURL?: string;
authenticated?: boolean;
} = {}) {
this.baseURL = baseURL;
this.authenticated = authenticated;
this.alias = new AliasEndpoint(this.baseURL, this.authenticated);
this.eval = new EvalEndpoint(this.baseURL, this.authenticated);
this.me = new MeEndpoint(this.baseURL, this.authenticated);
this.users = new UsersEndpoint(this.baseURL, this.authenticated);
this.vals = new ValsEndpoint(this.baseURL, this.authenticated);
this.run = new RunEndpoint(this.baseURL, this.authenticated);
this.endpoint = new Endpoint(this.baseURL, this.authenticated);
}
}
class Endpoint {
protected baseURL: string;
protected route: string;
private authenticated: boolean;
constructor(baseURL: string, authenticated: boolean) {
this.baseURL = baseURL;
this.route = "";
this.authenticated = authenticated;
}
protected async apiCall<T>(
path: string,
init: RequestInit & {
authenticated?: boolean;
} = { authenticated: this.authenticated },
): Promise<T> {
const authenticated = init.authenticated !== undefined
? init.authenticated
: this.authenticated;
const authorization = authenticated
? `Bearer ${Deno.env.get("valtown")}`
: undefined;
try {
const response = await fetch(`${this.baseURL}${path}`, {
...init,
headers: {
...init.headers,
Authorization: authorization as string,
},
});
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data: T = await response.json();
return data;
} catch (error) {
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.