-
Notifications
You must be signed in to change notification settings - Fork 4
/
store.js
62 lines (54 loc) · 1.73 KB
/
store.js
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
import fetch from 'unfetch'
// Get the host from R4 or production or staging.
const getHost = () => {
if (window && window.r4 && window.r4.databaseURL) {
return window.r4.databaseURL
}
if (process.env.NODE_ENV === 'production') {
return 'https://radio4000.firebaseio.com'
}
return 'https://radio4000-staging.firebaseio.com'
}
const host = getHost()
// Utilities for working with Firebase REST API.
const parse = res => {
if (!res) return null
return res.json().then(json => {
if (!json) return null
if (!Object.keys(json).length) throw new Error('404')
return json
})
}
const serializeId = (data, id) => {
if (data) {
return Object.assign(data, {id})
}
}
const toArray = firebaseObj => {
return Object.keys(firebaseObj).map(id => {
return Object.assign(firebaseObj[id], {id})
})
}
const getFirst = arr => arr[0]
export function findChannelBySlug(slug) {
const url = `${host}/channels.json?orderBy="slug"&startAt="${slug}"&endAt="${slug}"`
return fetch(url).then(parse).then(toArray).then(getFirst)
}
export function findChannelById(id) {
const url = `${host}/channels/${id}.json`
return fetch(url).then(parse).then(obj => serializeId(obj, id))
}
export function findChannelTracks(id) {
const url = `${host}/tracks.json?orderBy="channel"&startAt="${id}"&endAt="${id}"`
return fetch(url).then(parse).then(toArray).then(arr => {
// Firebase queries through REST are not sorted.
return arr.sort((a, b) => a.created - b.created)
})
}
export function findTrack(id) {
const url = `${host}/tracks/${id}.json`
return fetch(url).then(parse).then(data => serializeId(data, id))
}
export function buildThumbnail(cloudinaryId) {
return `https://res.cloudinary.com/radio4000/image/upload/w_250,h_250,q_60,c_thumb,fl_lossy/${cloudinaryId}`
}