Skip to content

Commit

Permalink
add method to refresh spotify token
Browse files Browse the repository at this point in the history
  • Loading branch information
IkeHunter committed Oct 17, 2024
1 parent f47b97f commit 06ed491
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions src/spotify/spotify.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BadRequestException, Injectable } from '@nestjs/common'
import { BadRequestException, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { SpotifyApi } from '@spotify/web-api-ts-sdk'
import { Axios } from 'axios'
Expand Down Expand Up @@ -105,19 +105,39 @@ export class SpotifyService {
link: { spotify_email: string } | SpotifyLink,
): Promise<SpotifyLink> {
let spotifyLink: SpotifyLink

if (!isSpotifyLink(link)) {
spotifyLink = (await this.findLinkFromEmail(link.spotify_email)) as SpotifyLink
} else {
spotifyLink = link
}

const sdk = this.getSdk(spotifyLink)
if (!spotifyLink.isExpired()) {
return spotifyLink
}

const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: spotifyLink.refresh_token,
})
const authBuffer = Buffer.from(SPOTIFY_CLIENT_ID + ':' + SPOTIFY_CLIENT_SECRET)

const tokens = await sdk.getAccessToken()
const res = await this.axios
.post('https://accounts.spotify.com/api/token', body, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic ' + authBuffer.toString('base64'),
},
})
.catch((error) => {
console.log('Error from axios spotify:', error)
throw new BadRequestException(error?.response?.data?.error_description || error)
})

spotifyLink.access_token = tokens.access_token
spotifyLink.expires_in = tokens.expires_in
spotifyLink.expires_at = new Date(tokens.expires)
spotifyLink.access_token = res.data.access_token
spotifyLink.expires_in = res.data.expires_in
spotifyLink.syncExpiresAt()
Logger.debug('Refreshed spotify token.')

await spotifyLink.save()
return spotifyLink
Expand Down

0 comments on commit 06ed491

Please sign in to comment.