summaryrefslogtreecommitdiff
path: root/src/connector.js
blob: 03e6f3dbabe1a2cdd339483faf390d2aa536aa16 (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
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) {
		return fetch(this.url + "/api" + endpoint)
	}

	fetch(endpoint) {
		return this.#fetch(endpoint)
			.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)
			})
	}

	seek(increment) {
		//return this.fetch(`/seek?increment=${increment}`)
		this.socket.emit("seek", increment)
	}

	fetchAlbums() {
		return this.fetch("/albums")
	}

	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