Skip to content

armgit / my-yt

Public Imported from GitHub
0

A clean and minimal youtube frontend, without all the ads and whistles

JavaScript

refactor: introduce API client abstraction (Refactoring #2)

Christian Fei135f971aa992
diff --git a/client/components/forms/add-channel-form.js b/client/components/forms/add-channel-form.js
index ac6fba9..ac68a01 100644
--- a/client/components/forms/add-channel-form.js
+++ b/client/components/forms/add-channel-form.js
@@ -1,4 +1,6 @@
/* global HTMLElement, customElements, alert */
+import { ENDPOINTS } from '../../lib/api.js'
+
class AddChannelForm extends HTMLElement {
connectedCallback () {
this.render()
@@ -44,7 +46,7 @@ class AddChannelForm extends HTMLElement {
freezeForm()
- fetch('/api/channels', {
+ fetch(ENDPOINTS.CHANNELS, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: channelName })
diff --git a/client/components/forms/excluded-terms-form.js b/client/components/forms/excluded-terms-form.js
index 3676665..8b251d2 100644
--- a/client/components/forms/excluded-terms-form.js
+++ b/client/components/forms/excluded-terms-form.js
@@ -1,4 +1,6 @@
/* global HTMLElement, customElements, confirm */
+import { ENDPOINTS } from '../../lib/api.js'
+
class ExcludedTermsForm extends HTMLElement {
connectedCallback () {
this.render()
@@ -43,7 +45,7 @@ class ExcludedTermsForm extends HTMLElement {
event.preventDefault()
const term = event.target.value.trim()
if (event.key === 'Enter' && term) {
- fetch('/api/excluded-terms', {
+ fetch(ENDPOINTS.EXCLUDED_TERMS, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ term })
@@ -57,7 +59,7 @@ class ExcludedTermsForm extends HTMLElement {
}
fetchExcludedTermsHandler () {
- fetch('/api/excluded-terms')
+ fetch(ENDPOINTS.EXCLUDED_TERMS)
.then(response => response.json())
.then(data => {
const $excludedTerms = this.querySelector('#excluded-terms')
@@ -69,7 +71,7 @@ class ExcludedTermsForm extends HTMLElement {
$excludedTerms.appendChild($li)
$li.addEventListener('click', () => {
if (!confirm('Remove "' + term + '" from excluded terms?')) return
- fetch('/api/excluded-terms', {
+ fetch(ENDPOINTS.EXCLUDED_TERMS, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ term })
diff --git a/client/components/forms/manage-channels-form.js b/client/components/forms/manage-channels-form.js
index d584a17..4382787 100644
--- a/client/components/forms/manage-channels-form.js
+++ b/client/components/forms/manage-channels-form.js
@@ -1,5 +1,6 @@
/* global HTMLElement, customElements, alert, confirm */
import { addClickListener, removeClickListener } from '../../lib/utils.js'
+import { ENDPOINTS } from '../../lib/api.js'
class ManageChannelsForm extends HTMLElement {
connectedCallback () {
this.render()
@@ -11,7 +12,7 @@ class ManageChannelsForm extends HTMLElement {
}
fetchData () {
- fetch('/api/channels')
+ fetch(ENDPOINTS.CHANNELS)
.then(res => res.json())
.then(channels => {
const $container = this.querySelector('#manage-channels')
@@ -51,7 +52,7 @@ class ManageChannelsForm extends HTMLElement {
if (!channelName) return alert('empty channel name')
if (!confirm(`Do you want to delete the channel ${channelName}?`)) return
- fetch('/api/channels', {
+ fetch(ENDPOINTS.CHANNELS, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: channelName })
diff --git a/client/components/forms/manage-disk-space-form.js b/client/components/forms/manage-disk-space-form.js
index 70c126d..8f7112c 100644
--- a/client/components/forms/manage-disk-space-form.js
+++ b/client/components/forms/manage-disk-space-form.js
@@ -1,4 +1,6 @@
/* global HTMLElement, customElements, confirm */
+import { ENDPOINTS } from '../../lib/api.js'
+
class ManageDiskSpaceForm extends HTMLElement {
connectedCallback () {
this.render()
@@ -43,7 +45,7 @@ class ManageDiskSpaceForm extends HTMLElement {
updateDiskSpaceUsed () {
const onlyIgnored = this.querySelector('#delete-only-ignored').checked
const $diskUsage = this.querySelector('#disk-usage')
- fetch(onlyIgnored ? '/api/disk-usage?onlyIgnored=true' : '/api/disk-usage')
+ fetch(onlyIgnored ? `${ENDPOINTS.DISK_USAGE}?onlyIgnored=true` : ENDPOINTS.DISK_USAGE)
.then(response => response.text())
.then((diskSpaceUsed) => {
$diskUsage.innerHTML = /* html */`Currently <span id="disk-space-used">${diskSpaceUsed}</span> of disk space used`
@@ -56,7 +58,7 @@ class ManageDiskSpaceForm extends HTMLElement {
if (!confirm('About to delete downloaded videos, are you sure?')) return
const onlyIgnored = this.querySelector('#delete-only-ignored').checked
const $diskUsage = this.querySelector('#disk-usage')
- fetch('/api/reclaim-disk-space', {
+ fetch(ENDPOINTS.RECLAIM_DISK_SPACE, {
method: 'POST',
body: JSON.stringify({ onlyIgnored })
})
diff --git a/client/components/forms/transcode-videos-form.js b/client/components/forms/transcode-videos-form.js
index 36846e9..0299139 100644
--- a/client/components/forms/transcode-videos-form.js
+++ b/client/components/forms/transcode-videos-form.js
@@ -1,10 +1,12 @@
/* global HTMLElement, customElements */
+import { ENDPOINTS } from '../../lib/api.js'
+
class TranscodeVideosForm extends HTMLElement {
connectedCallback () {
this.render()
this.registerEvents()
- fetch('/api/transcode-videos')
+ fetch(ENDPOINTS.TRANSCODE_VIDEOS)
.then(response => response.json())
.then((transcodeVideos) => {
this.querySelector('#transcode-videos').checked = transcodeVideos
@@ -41,7 +43,7 @@ class TranscodeVideosForm extends HTMLElement {
setTranscodeVideosHandler (event) {
event.preventDefault()
- fetch('/api/transcode-videos', {
+ fetch(ENDPOINTS.TRANSCODE_VIDEOS, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event.target.checked)
diff --git a/client/components/forms/video-quality-form.js b/client/components/forms/video-quality-form.js
index 72f5da7..8c29a5f 100644
--- a/client/components/forms/video-quality-form.js
+++ b/client/components/forms/video-quality-form.js
@@ -1,10 +1,12 @@
/* global HTMLElement, customElements */
+import { ENDPOINTS } from '../../lib/api.js'
+
class VideoQualityForm extends HTMLElement {
connectedCallback () {
this.render()
this.registerEvents()
- fetch('/api/video-quality')
+ fetch(ENDPOINTS.VIDEO_QUALITY)
.then(response => response.json())
.then((videoQuality) => {
this.querySelector('#video-quality').value = +videoQuality
@@ -46,7 +48,7 @@ class VideoQualityForm extends HTMLElement {
setVideoQualityHandler (event) {
event.preventDefault()
- fetch('/api/video-quality', {
+ fetch(ENDPOINTS.VIDEO_QUALITY, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: event.target.value
diff --git a/client/components/search-videos.js b/client/components/search-videos.js
index 8148501..faeb392 100644
--- a/client/components/search-videos.js
+++ b/client/components/search-videos.js
@@ -1,5 +1,6 @@
/* global HTMLElement, customElements, document */
import { addToast } from '../lib/utils.js'
+import { ENDPOINTS } from '../lib/api.js'
const searchEventSupported = 'search' in document.createElement('input')
console.log({ searchEventSupported })
@@ -88,7 +89,7 @@ class SearchVideos extends HTMLElement {
if (searchTerm.match('https?://')) {
addToast('Downloading video...')
- fetch('/api/download-video', {
+ fetch(ENDPOINTS.DOWNLOAD_VIDEO, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: searchTerm, external: true })
@@ -119,7 +120,7 @@ class SearchVideos extends HTMLElement {
const query = `?filter=${encodeURIComponent(searchTerm)}${excluded ? '&excluded=true' : ''}${downloaded ? '&downloaded=true' : ''}${ignored ? '&ignored=true' : ''}${summarized ? '&summarized=true' : ''}`
window.history.pushState({}, '', query)
- fetch(`/api/videos${query}`)
+ fetch(ENDPOINTS.VIDEOS + query)
.then(res => res.json())
.then((videos) => {
const $videosContainer = document.querySelector('videos-container')
diff --git a/client/components/video-element.js b/client/components/video-element.js
index ba8fd6a..0643b97 100644
--- a/client/components/video-element.js
+++ b/client/components/video-element.js
@@ -1,6 +1,7 @@
/* global HTMLElement, customElements, confirm */
import { addClickListener, removeClickListener, addToast } from '../lib/utils.js'
import Store from '../lib/store.js'
+import { ENDPOINTS } from '../lib/api.js'
const store = new Store()
class VideoElement extends HTMLElement {
@@ -135,13 +136,13 @@ class VideoElement extends HTMLElement {
event.preventDefault()
this.querySelector('.play.video-placeholder').outerHTML = /* html */`
<video controls playsinline style="user-select: none; width: 100%;">
- <source src="/api/videos/${this.video.id}.${this.video.format || 'mp4'}" type="video/${this.video.format || 'mp4'}" />
+ <source src="${ENDPOINTS.VIDEOS}/${this.video.id}.${this.video.format || 'mp4'}" type="video/${this.video.format || 'mp4'}" />
${store.get(store.showCaptionsKey)
- ? /* html */`<track default kind="captions" srclang="en" src="/api/captions/${this.video.id}" />`
+ ? /* html */`<track default kind="captions" srclang="en" src="${ENDPOINTS.CAPTIONS}/${this.video.id}" />`
: ''}
<p>
Your browser does not support the video tag.
- Download the video instead <a href="/api/videos/${this.video.id}" target="_blank">here</a>
+ Download the video instead <a href="${ENDPOINTS.VIDEOS}/${this.video.id}" target="_blank">here</a>
</p>
</video>`
@@ -160,7 +161,7 @@ class VideoElement extends HTMLElement {
addToast('Downloading video...')
- fetch('/api/download-video', {
+ fetch(ENDPOINTS.DOWNLOAD_VIDEO, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: this.video.id })
@@ -171,7 +172,7 @@ class VideoElement extends HTMLElement {
deleteVideoHandler (event) {
event.preventDefault()
if (!confirm('About to delete video files, are you sure?')) return
- fetch('/api/delete-video', {
+ fetch(ENDPOINTS.DELETE_VIDEO, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: this.video.id })
@@ -196,7 +197,7 @@ class VideoElement extends HTMLElement {
addToast('Summarizing video...')
- fetch('/api/summarize-video', {
+ fetch(ENDPOINTS.SUMMARIZE_VIDEO, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: this.video.id })
@@ -222,7 +223,7 @@ class VideoElement extends HTMLElement {
toggleIgnoreVideoHandler (event) {
event.preventDefault()
- fetch('/api/ignore-video', {
+ fetch(ENDPOINTS.IGNORE_VIDEO, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: this.video.id, ignore: !this.video.ignored })
diff --git a/client/lib/api.js b/client/lib/api.js
new file mode 100644
index 0000000..cbe9367
--- /dev/null
+++ b/client/lib/api.js
@@ -0,0 +1,36 @@
+// Shared API client abstraction — eliminates hardcoded /api/* strings across all components.
+
+export const ENDPOINTS = {
+ CHANNELS: '/api/channels',
+ CAPTIONS: '/api/captions',
+ DOWNLOAD_VIDEO: '/api/download-video',
+ SUMMARIZE_VIDEO: '/api/summarize-video',
+ IGNORE_VIDEO: '/api/ignore-video',
+ DELETE_VIDEO: '/api/delete-video',
+ VIDEOS: '/api/videos',
+ VIDEO_QUALITY: '/api/video-quality',
+ DISK_USAGE: '/api/disk-usage',
+ RECLAIM_DISK_SPACE: '/api/reclaim-disk-space',
+ TRANSCODE_VIDEOS: '/api/transcode-videos',
+ EXCLUDED_TERMS: '/api/excluded-terms'
+}
+
+export class ApiClient {
+ constructor (base = '') { this.base = base }
+
+ get (path, params = {}) {
+ const query = new URLSearchParams(params).toString()
+ const url = query ? `${this.base}${path}?${query}` : `${this.base}${path}`
+ return fetch(url).then(r => r.json())
+ }
+
+ post (path, body) {
+ return fetch(`${this.base}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ }).then(r => r.json())
+ }
+}
+
+export const api = new ApiClient() // singleton exported to all components via import
diff --git a/client/lib/router.js b/client/lib/router.js
index 130b588..b352f9b 100644
--- a/client/lib/router.js
+++ b/client/lib/router.js
@@ -1,6 +1,7 @@
/* global MutationObserver, history, PopStateEvent, location, dispatchEvent */
import { applyShowBigPlayer, applyShowThumbnails } from '../lib/utils.js'
import Store from '../lib/store.js'
+import { ENDPOINTS } from '../lib/api.js'
const store = new Store()
const routes = {
@@ -14,7 +15,7 @@ const routes = {
document.querySelector('search-videos').searchHandler()
- const channels = await fetch('/api/channels').then(res => res.json())
+ const channels = await fetch(ENDPOINTS.CHANNELS).then(res => res.json())
document.querySelector('channels-list').dataset.list = JSON.stringify(channels.map(c => c.name).filter(Boolean))
document.querySelector('empty-state').dataset.hasChannels = channels.length > 0
diff --git a/client/test/search-videos.test.js b/client/test/search-videos.test.js
index 20f0b4d..d7d72f3 100644
--- a/client/test/search-videos.test.js
+++ b/client/test/search-videos.test.js
@@ -3,6 +3,7 @@ import sinon from 'sinon'
import { fixture, html, assert } from '@open-wc/testing'
import '../components/search-videos.js'
+import { ENDPOINTS } from '../lib/api.js'
describe('search-videos', () => {
it('makes HTTP request to API with search term', async () => {
@@ -19,6 +20,6 @@ describe('search-videos', () => {
$search.dispatchEvent(new Event('input'))
assert.equal(fetchStub.callCount, 1)
- assert.equal(fetchStub.args[0][0], '/api/videos?filter=test')
+ assert.equal(fetchStub.args[0][0], ENDPOINTS.VIDEOS + '?filter=test')
})
})