Skip to content

Commit 741f801

Browse files
committed
Make fetch requests using route-provided fetch() function
https://svelte.dev/docs/kit/load#Making-fetch-requests
1 parent f98073f commit 741f801

19 files changed

Lines changed: 117 additions & 88 deletions

File tree

Site/src/hooks.server.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ export async function handle(e) {
119119
)
120120
redirect(302, "/moderation")
121121

122-
await stipend(user.id)
122+
await stipend(e.event.fetch, user.id)
123123

124124
return await finish(e)
125125
}

Site/src/lib/server/economy.ts

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,12 @@ export type ReturnErr = { ok: true } | { ok: false; msg: string }
1010

1111
const tryFetch =
1212
<T>(transform: (res: Response) => Promise<T>) =>
13-
async (url: string): Promise<ReturnValue<T>> => {
13+
async (
14+
f: typeof globalThis.fetch,
15+
url: string
16+
): Promise<ReturnValue<T>> => {
1417
try {
15-
const res = await fetch(url)
18+
const res = await f(url)
1619
if (!res.ok) return { ok: false }
1720
return { ok: true, value: await transform(res) }
1821
} catch {
@@ -23,9 +26,10 @@ const tryFetch =
2326
const tryFetchValue = tryFetch(async res => +(await res.text()))
2427
const tryFetchJson = <T>() => tryFetch(async res => (await res.json()) as T) // type assertion much?¿
2528

26-
export const getStipend = () => tryFetchValue(`${economyUrl}/currentStipend`)
27-
export const getBalance = (user: string) =>
28-
tryFetchValue(`${economyUrl}/balance/${user}`)
29+
export const getStipend = (f: typeof globalThis.fetch) =>
30+
tryFetchValue(f, `${economyUrl}/currentStipend`)
31+
export const getBalance = (f: typeof globalThis.fetch, user: string) =>
32+
tryFetchValue(f, `${economyUrl}/balance/${user}`)
2933

3034
type BaseTx = {
3135
Note: string
@@ -58,21 +62,20 @@ type TxTypes =
5862

5963
type ReceivedTx = BaseTx & TxTypes
6064

61-
export const getTransactions = (user: string) =>
62-
tryFetchJson<ReceivedTx[]>()(`${economyUrl}/transactions/${user}`)
63-
export const getAdminTransactions = () =>
64-
tryFetchJson<ReceivedTx[]>()(`${economyUrl}/transactions`)
65+
export const getTransactions = (f: typeof globalThis.fetch, user: string) =>
66+
tryFetchJson<ReceivedTx[]>()(f, `${economyUrl}/transactions/${user}`)
67+
export const getAdminTransactions = (f: typeof globalThis.fetch) =>
68+
tryFetchJson<ReceivedTx[]>()(f, `${economyUrl}/transactions`)
6569

6670
// doin nothing with returns rn
67-
export async function stipend(To: string) {
71+
export async function stipend(f: typeof globalThis.fetch, To: string) {
6872
try {
69-
await fetch(`${economyUrl}/stipend/${To}`, {
70-
method: "post",
71-
})
73+
await f(`${economyUrl}/stipend/${To}`, { method: "post" })
7274
} catch {}
7375
}
7476

7577
export async function transact(
78+
f: typeof globalThis.fetch,
7679
From: string,
7780
To: string,
7881
Amount: number,
@@ -81,7 +84,7 @@ export async function transact(
8184
Returns: { [_: number]: number }
8285
): Promise<ReturnErr> {
8386
try {
84-
const res = await fetch(`${economyUrl}/transact`, {
87+
const res = await f(`${economyUrl}/transact`, {
8588
method: "post",
8689
body: JSON.stringify({ From, To, Amount, Note, Link, Returns }),
8790
})
@@ -94,6 +97,7 @@ export async function transact(
9497
}
9598

9699
async function burn(
100+
f: typeof globalThis.fetch,
97101
From: string,
98102
Amount: number,
99103
Note: string,
@@ -106,7 +110,7 @@ async function burn(
106110
// When my campaign turned to a cam-pain
107111
// We got $2.5 trillion stored on the blockchain
108112
// Uh, ₿urn ₿aby ₿urn
109-
const res = await fetch(`${economyUrl}/burn`, {
113+
const res = await f(`${economyUrl}/burn`, {
110114
method: "post",
111115
body: JSON.stringify({ From, Amount, Note, Link, Returns }),
112116
})
@@ -127,13 +131,15 @@ export const getGroupPrice = () => getFeeBasedPrice(50)
127131
// export const getPlacePrice = () => getFeeBasedPrice(50)
128132

129133
export async function createAsset(
134+
f: typeof globalThis.fetch,
130135
To: string,
131136
id: number,
132137
name: string,
133138
slug: string
134139
): Promise<ReturnErr> {
135140
const price = getAssetPrice()
136141
return await burn(
142+
f,
137143
To,
138144
price,
139145
`Created asset ${name}`,
@@ -143,13 +149,15 @@ export async function createAsset(
143149
}
144150

145151
// export async function createPlace(
152+
// f: typeof globalThis.fetch,
146153
// To: string,
147154
// id: number,
148155
// name: string,
149156
// slug: string
150157
// ): Promise<ReturnErr> {
151158
// const price = getPlacePrice()
152159
// return await burn(
160+
// fee,
153161
// To,
154162
// price,
155163
// `Created place ${name}`,
@@ -159,11 +167,19 @@ export async function createAsset(
159167
// }
160168

161169
export async function createGroup(
170+
f: typeof globalThis.fetch,
162171
To: string,
163172
name: string
164173
): Promise<ReturnErr> {
165174
const price = getGroupPrice()
166-
return await burn(To, price, `Created group ${name}`, `/groups/${name}`, {})
175+
return await burn(
176+
f,
177+
To,
178+
price,
179+
`Created group ${name}`,
180+
`/groups/${name}`,
181+
{}
182+
)
167183
}
168184

169185
export async function transformTransactions(list: ReceivedTx[]) {

Site/src/lib/server/orbiter.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ type Gameserver = {
88

99
type GameserverId = [number, Gameserver]
1010

11-
export async function listGameservers(): ReturnValue<GameserverId[]> {
11+
export async function listGameservers(
12+
f: typeof globalThis.fetch
13+
): ReturnValue<GameserverId[]> {
1214
try {
13-
const res = await fetch(config.OrbiterPrivateURL)
15+
const res = await f(config.OrbiterPrivateURL)
1416
if (!res.ok) return { ok: false }
1517
return { ok: true, value: await res.json() }
1618
} catch {
@@ -19,11 +21,12 @@ export async function listGameservers(): ReturnValue<GameserverId[]> {
1921
}
2022

2123
async function fetchGameserver(
24+
f: typeof globalThis.fetch,
2225
path: string | number,
2326
method: string
2427
): Promise<ReturnErr> {
2528
try {
26-
const res = await fetch(`${config.OrbiterPrivateURL}/${path}`, { method })
29+
const res = await f(`${config.OrbiterPrivateURL}/${path}`, { method })
2730
if (!res.ok) return { ok: false, msg: await res.text() }
2831
} catch (err) {
2932
const e = err as Error
@@ -32,8 +35,12 @@ async function fetchGameserver(
3235
return { ok: true }
3336
}
3437

35-
export const startGameserver = async (placeId: number) =>
36-
fetchGameserver(placeId, "put")
38+
export const startGameserver = async (
39+
f: typeof globalThis.fetch,
40+
placeId: number
41+
) => fetchGameserver(f, placeId, "put")
3742

38-
export const closeGameserver = async (placeId: number) =>
39-
fetchGameserver(placeId, "delete")
43+
export const closeGameserver = async (
44+
f: typeof globalThis.fetch,
45+
placeId: number
46+
) => fetchGameserver(f, placeId, "delete")

Site/src/lib/server/requestRender.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ type Render = {
2020
* @param wait Whether to wait for the render to be completed before resolving.
2121
*/
2222
export default async function (
23+
f: typeof globalThis.fetch,
2324
renderType: RenderType,
2425
relativeId: string | number,
2526
relativeName = relativeId,
@@ -85,7 +86,7 @@ export default async function (
8586
await Promise.all([
8687
waiter,
8788
// Uhh carrot just got the
88-
fetch(`${config.RCCServiceProxyURL}/${renderId}`, {
89+
f(`${config.RCCServiceProxyURL}/${renderId}`, {
8990
method: "post",
9091
body: script,
9192
}),

Site/src/routes/(main)/admin/asset/+page.server.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ actions.rerender = async e => {
8080
if (limit) return limit
8181

8282
try {
83-
await requestRender("Clothing", id)
83+
await requestRender(e.fetch, "Clothing", id)
8484
} catch (e) {
8585
console.error(e)
8686
fail(500, { msg: "Failed to request render" })

Site/src/routes/(main)/admin/create/+page.server.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ actions.default = async ({ locals, request }) => {
4646
if (!fs.existsSync("../data/thumbnails")) fs.mkdirSync("../data/thumbnails")
4747

4848
const { asset, description, name, price, type: assetType } = data
49-
form.data.asset = null // make sure to return as a POJO
49+
form.data.asset = null as unknown as File// make sure to return as a POJO
5050

5151
const [, id] = await db.query<string[]>(createQuery, {
5252
description,
@@ -59,7 +59,7 @@ actions.default = async ({ locals, request }) => {
5959
await Bun.write(`../data/assets/${id}`, await asset.arrayBuffer())
6060

6161
// we'll just assume it's a model 4 now
62-
// await requestRender("Model", id)
62+
// await requestRender(f, "Model", id)
6363

6464
redirect(302, `/catalog/${id}`)
6565
}

Site/src/routes/(main)/admin/gameservers/+page.server.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ import { error } from "@sveltejs/kit"
22
import { authorise } from "$lib/server/auth"
33
import { listGameservers } from "$lib/server/orbiter"
44

5-
export async function load({ locals }) {
5+
export async function load({ fetch: f, locals }) {
66
await authorise(locals, 5)
77

8-
const gameservers = await listGameservers()
8+
const gameservers = await listGameservers(f)
99
if (!gameservers.ok) error(500, "Failed to fetch gameservers")
1010

1111
return {

Site/src/routes/(main)/catalog/[id=asset]/[name]/+page.server.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ const noTexts = Object.freeze([
5454
])
5555
const failTexts = Object.freeze(["Bruh", "Okay", "Aight", "Rip", "Aw man..."])
5656

57-
export async function load({ locals, params }) {
57+
export async function load({ fetch: f, locals, params }) {
5858
const { user } = await authorise(locals)
5959
const id = +params.id
6060
const [[asset]] = await db.query<Asset[][]>(assetQuery, {
@@ -67,7 +67,7 @@ export async function load({ locals, params }) {
6767
if (!couldMatch(asset.name, params.name))
6868
redirect(302, `/catalog/${id}/${slug}`)
6969

70-
const balance = await getBalance(user.id)
70+
const balance = await getBalance(f, user.id)
7171
if (!balance.ok) error(500, economyConnFailed)
7272

7373
return {
@@ -91,7 +91,7 @@ async function getBuyData(e: RequestEvent) {
9191
}
9292

9393
// actions that return things are here because of sveltekit typescript limitations
94-
async function rerender({ locals, params }: RequestEvent) {
94+
async function rerender({ fetch: f, locals, params }: RequestEvent) {
9595
await authorise(locals, 5)
9696

9797
const id = +params.id
@@ -109,7 +109,7 @@ async function rerender({ locals, params }: RequestEvent) {
109109

110110
if ([8, 11, 12].includes(asset.type))
111111
try {
112-
await requestRender(asset.type === 8 ? "Model" : "Clothing", id)
112+
await requestRender(f, asset.type === 8 ? "Model" : "Clothing", id)
113113
const icon = `/catalog/${id}/${asset.name}/icon?r=${Math.random()}`
114114
return { icon }
115115
} catch (e) {
@@ -185,6 +185,7 @@ actions.buy = async e => {
185185
if (asset.price > 0) {
186186
// todo work out how free assets are supposed to work
187187
const tx = await transact(
188+
e.fetch,
188189
user.id,
189190
asset.creator.id,
190191
asset.price,

Site/src/routes/(main)/character/+page.server.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ async function getEquipData(e: RequestEvent) {
7272
return { user, id, asset }
7373
}
7474

75-
async function rerender(user: User) {
75+
async function rerender(f: typeof globalThis.fetch, user: User) {
7676
try {
77-
await requestRender("Avatar", user.id, user.username, true)
77+
await requestRender(f, "Avatar", user.id, user.username, true)
7878
return {
7979
avatar: `/api/avatar/${user.username}-body?r=${Math.random()}`,
8080
}
@@ -84,7 +84,7 @@ async function rerender(user: User) {
8484
}
8585
}
8686

87-
async function paint({ locals, url }: RequestEvent) {
87+
async function paint({ fetch: f, locals, url }: RequestEvent) {
8888
const { user } = await authorise(locals)
8989
const bodyPartQuery = url.searchParams.get("p")
9090
const bodyColour = url.searchParams.get("c") as string
@@ -104,15 +104,15 @@ async function paint({ locals, url }: RequestEvent) {
104104

105105
db.merge(Record("user", user.id), { bodyColours: currentColours })
106106

107-
return await rerender(user)
107+
return await rerender(f, user)
108108
}
109-
async function regen({ locals, getClientAddress }: RequestEvent) {
109+
async function regen({ fetch: f, locals, getClientAddress }: RequestEvent) {
110110
const { user } = await authorise(locals)
111111

112112
const limit = ratelimit(null, "regen", getClientAddress, 2)
113113
if (limit) return limit
114114

115-
return await rerender(user)
115+
return await rerender(f, user)
116116
}
117117
async function equip(e: RequestEvent) {
118118
const { user, id, asset, error } = await getEquipData(e)
@@ -133,7 +133,7 @@ async function equip(e: RequestEvent) {
133133
...(oneEquippable.includes(asset.type) ? asset : {}),
134134
})
135135

136-
return await rerender(user)
136+
return await rerender(e.fetch, user)
137137
}
138138
async function unequip(e: RequestEvent) {
139139
const { user, id, error } = await getEquipData(e)
@@ -144,7 +144,7 @@ async function unequip(e: RequestEvent) {
144144
asset: Record("asset", id),
145145
})
146146

147-
return await rerender(user)
147+
return await rerender(e.fetch, user)
148148
}
149149
export const actions: import("./$types").Actions = {
150150
paint,

0 commit comments

Comments
 (0)