Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
// This val uses Val Town's Blob storage to maintain a shared global integer value.
// We'll use the val's URL as the storage key for consistency.
// The main function handles both GET requests to retrieve the current value
// and POST requests to increment the value.
// We're using Promises with .then() instead of async/await for asynchronous operations.
import { blob } from "https://esm.town/v/std/blob";
// const KEY = new URL(import.meta.url).pathname;
const KEY = "Ben Wheeler globalIncrement test key";
export function getValue(): Promise<number> {
return blob.getJSON(KEY)
.then(value => typeof value === "number" ? value : 0)
.catch(() => 0);
}
export function increment(): Promise<number> {
return getValue()
.then(currentValue => {
const newValue = currentValue + 1;
return blob.setJSON(KEY, newValue)
.then(() => {
console.log(`Previous value: ${currentValue} ; Updated value: ${newValue}`);
return newValue;
});
});
}
export default async function(req: Request): Promise<Response> {
if (req.method === "POST") {
return increment()
.then(newValue => Response.json({ value: newValue }));
} else {
return getValue()
.then(currentValue => Response.json({ value: currentValue }));
}
// return Response.json({ ok: true });
}
export function checkIfWorking(req: Request): Promise<Response> {
console.log("working");
}
// export function main(req: Request): Promise<Response> {
// }
benjiwheeler-globalincrement.web.val.run
August 29, 2024