Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle backend errors #14

Merged
merged 10 commits into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/functions-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- run: echo ${{ github.event_name }}
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version-file: 'functions/.nvmrc'
- name: Install dependencies
run: yarn --cwd ./functions/
- name: Build
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/functions-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version-file: 'functions/.nvmrc'
- name: Install dependencies
run: yarn --cwd ./functions/
- name: Download Artifact
Expand Down
10 changes: 10 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"console": "integratedTerminal",
"preLaunchTask": "npm: build - functions"
},
{
"name": "Attach Firebase Functions Emulator",
"type": "node",
"request": "attach",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/functions/lib/**/*.js"],
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"cwd": "${workspaceFolder}/functions",
"port": 9229
}
]
}
8 changes: 5 additions & 3 deletions functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"build:watch": "tsc --watch",
"serve": "yarn build && firebase emulators:start --only functions,firestore,pubsub -P dev",
"dev": "yarn build && firebase emulators:start --only functions,firestore,pubsub --inspect-functions -P dev",
"shell": "yarn build && firebase functions:shell -P dev",
"shell-prep": "yarn build && firebase emulators:start --only firestore,pubsub -P dev",
"shell": "yarn build && firebase functions:shell -P dev --inspect-functions",
"start": "yarn shell",
"deploy": "firebase deploy --only functions -P prod",
"logs": "firebase functions:log"
Expand All @@ -17,10 +18,11 @@
"dependencies": {
"firebase-admin": "^10.2.0",
"firebase-functions": "^4.1.1",
"spotify-web-api-node": "^5.0.2"
"node-fetch": "^2.6.7"
},
"devDependencies": {
"@types/spotify-web-api-node": "^5.0.7",
"@types/node-fetch": "^2.6.4",
"@types/spotify-api": "^0.0.22",
"typescript": "^4.9.4"
},
"private": true
Expand Down
12 changes: 0 additions & 12 deletions functions/src/authorize.ts

This file was deleted.

17 changes: 17 additions & 0 deletions functions/src/spotify/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { Response } from 'node-fetch'

export const handleRepsonse = async <T>(method: () => Promise<Response>): Promise<T> => {
const res = await method()
if (res.status < 300) {
if (res.headers.get('content-type')?.startsWith('application/json')) return await res.json()
else return true as T
} else {
let error
try {
error = (await res.json()).error
} catch {
error = { status: res.status, statusText: res.statusText }
}
throw error
}
}
182 changes: 182 additions & 0 deletions functions/src/spotify/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { handleRepsonse } from './error'
import fetch, { BodyInit } from 'node-fetch'

export class Spotify {
private credentials: Credentials
setRefreshToken(value: string) {
this.credentials.refreshToken = value
}

constructor(credentials: Credentials) {
this.credentials = credentials
}

private authRequest<T>(params: Record<string, string>): Promise<T> {
const { clientId, clientSecret } = this.credentials
if (!clientId || !clientSecret) throw new Error('Missing credentials')
return handleRepsonse<T>(() =>
fetch('https://accounts.spotify.com/api/token', {
headers: {
Authorization:
'Basic ' + Buffer.from(clientId + ':' + clientSecret).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: new URLSearchParams(params).toString()
})
)
}

private async request<T>(
endpoint: string,
method: 'GET',
params?: Record<string, Primative>
): Promise<T>
private async request<T>(
endpoint: string,
method: 'POST' | 'PUT' | 'DELETE',
params?: Record<string, Primative | Primative[]>
): Promise<T>
private async request<T>(
endpoint: string,
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
params?: Record<string, Primative | Primative[]>
): Promise<T> {
if (!this.credentials.accessToken)
throw new Error('Missing access token. Please authenticate first.')
let url = 'https://api.spotify.com/v1/' + endpoint
let body: BodyInit
if (method == 'GET' && params) {
for (const key in params) if (params[key]) params[key] = params[key]?.toString()
url += '?' + new URLSearchParams(params as Record<string, string>).toString()
} else if (params) {
body = JSON.stringify(params)
}
return await handleRepsonse<T>(() =>
fetch(url, {
headers: { Authorization: 'Bearer ' + this.credentials.accessToken },
method,
body
})
)
}

private async requestAll<T>(endpoint: string): Promise<T[]> {
const limit = 50
const { items, total } = await this.request<SpotifyApi.PagingObject<T>>(endpoint, 'GET', {
limit
})
const reqN = [...Array(Math.ceil(total / limit)).keys()] // number of request that need to be run
reqN.shift() // first request has already been run
const responses = await Promise.all(
reqN.map(i =>
this.request<SpotifyApi.PagingObject<T>>(endpoint, 'GET', {
limit,
offset: limit * i
})
)
)
items.push(...responses.flatMap(res => res.items))
return items
}

async authorizationCodeGrant(code: string) {
if (!this.credentials.redirectUri)
throw new Error('Missing redirect uri. Please authenticate first.')
const token = await this.authRequest<RefreshToken>({
code: code,
redirect_uri: this.credentials.redirectUri,
grant_type: 'authorization_code'
})
this.credentials.refreshToken = token.refresh_token
this.credentials.accessToken = token.access_token
return token
}

async refreshAccessToken() {
if (!this.credentials.refreshToken)
throw new Error('Missing refresh token. Please authenticate first.')
const token = await this.authRequest<AccessToken>({
refresh_token: this.credentials.refreshToken,
grant_type: 'refresh_token'
})
this.credentials.accessToken = token.access_token
}

getMe() {
return this.request<SpotifyApi.UserObjectPrivate>('me', 'GET')
}

getMySavedTracks() {
return this.requestAll<SpotifyApi.SavedTrackObject>('me/tracks')
}

getMyPlaylists() {
return this.requestAll<SpotifyApi.PlaylistObjectSimplified>('me/playlists')
}

createPlaylist(userId: string, details: PlaylistDetails) {
return this.request<SpotifyApi.PlaylistObjectFull>(
`users/${userId}/playlists`,
'POST',
details
)
}

changePlaylistDetails(playlistId: string, details: Partial<PlaylistDetails>) {
return this.request<void>('playlists/' + playlistId, 'PUT', details)
}

getPlaylistTracks(playlistId: string) {
return this.requestAll<SpotifyApi.PlaylistTrackObject>(`playlists/${playlistId}/tracks`)
}

addTracksToPlaylist(playlistId: string, uris: string[]) {
return this.request<SpotifyApi.PlaylistSnapshotResponse>(
`playlists/${playlistId}/tracks`,
'POST',
{ uris }
)
}

removeTracksToPlaylist(playlistId: string, uris: string[]) {
return this.request<SpotifyApi.PlaylistSnapshotResponse>(
`playlists/${playlistId}/tracks`,
'DELETE',
{ uris }
)
}

usersFollowPlaylist(playlistId: string, userIds: string[]) {
return this.request<boolean[]>(`playlists/${playlistId}/followers/contains`, 'GET', {
ids: userIds.join()
})
}
}

type Primative = string | number | boolean | undefined

interface Credentials {
accessToken?: string | undefined
clientId?: string | undefined
clientSecret?: string | undefined
redirectUri?: string | undefined
refreshToken?: string | undefined
}

interface AccessToken {
access_token: string
expires_in: number
scope: string
token_type: string
}

interface RefreshToken extends AccessToken {
refresh_token: string
}

type PlaylistDetails = {
name: string
description?: string
public?: boolean
}
Loading
Loading