summaryrefslogtreecommitdiff
path: root/src/connector.js
blob: 29f0cff4b2ad16e596a0085f68b81bf8278ed539 (plain)
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
import io from "socket.io-client"

class APIConnector {
	constructor(url) {
		this.url = url ?? ""
		this.socket = io(url)

		this.asset_index = 0
		this.movement = 0
		this.assets = null
		this.seekCallbacks = []

		this.socket.on("seek", e => {
			this.assetIndex = e.asset_index
			this.movement = e.movement
			this.assets = e.assets
			for (const cb of this.seekCallbacks)
				cb()
		})
	}

	fetch(endpoint, c) {
		return fetch(this.url + "/api" + endpoint, c ?? {})
			.then(response => {
				if (!response.ok)
					throw new Error(`HTTP error! Status: ${response.status}`)
				return response.json()
			})
			.then(data => {
				return data
			})
			.catch(error => {
				console.error("Fetch error:", error)
			})
	}

	post(endpoint, body) {
		return this.fetch(endpoint, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify(body),
		})
	}

	seek(increment) {
		this.socket.emit("seek", increment)
	}

	fetchAlbums() { return this.fetch("/albums") }
	fetchConfig() { return this.fetch("/config") }
	updateConfig(config) { return this.post("/config/update", config) }

	albumSrc(key)          { return `${this.url}/api/redirect/albums/${key}` }
	assetSrc(key)          { return `${this.url}/api/asset/${key}` }
	assetThumbnailSrc(key) { return `${this.url}/api/asset/${key}/thumbnail` }
}

const apiConnector = new APIConnector("http://localhost:5000")
export default apiConnector