Skip to content

Commit

Permalink
update deps
Browse files Browse the repository at this point in the history
  • Loading branch information
rocktimsaikia committed Apr 2, 2022
1 parent 17323e5 commit f43e1fb
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 56 deletions.
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
1 change: 1 addition & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
. "$(dirname "$0")/_/husky.sh"

npm test
npx lint-staged
26 changes: 11 additions & 15 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type CurrentlyPlayingOptions = {

type CurrentlyPlayingResponse = ResponseTrack & {
isPlaying: boolean;
}
};

const filterResponse = (track: Track): ResponseTrack => ({
title: track?.name,
Expand All @@ -33,6 +33,7 @@ const filterResponse = (track: Track): ResponseTrack => ({
});

const encodeToBase64 = (str: string): string => Buffer.from(str).toString('base64');

export class SpotifyClient {
private readonly clientId: string;
private readonly clientSecret: string;
Expand Down Expand Up @@ -67,14 +68,12 @@ export class SpotifyClient {
fallbackToLastPlayed = true
}: CurrentlyPlayingOptions = {}): Promise<CurrentlyPlayingResponse | null> => {
try {
if(this.accessToken === null)

this.accessToken = await this._genAccesToken();
if (this.accessToken === null) this.accessToken = await this._genAccesToken();

const headers = { Authorization: `Bearer ${this.accessToken}` };
const response = await fetch(CURRENTLY_PLAYING_URL, { headers });

if(response.status === 401) {
if (response.status === 401) {
this.accessToken = await this._genAccesToken();
return this.getCurrentlyPlaying({ fallbackToLastPlayed });
}
Expand All @@ -83,7 +82,7 @@ export class SpotifyClient {
if (response.status === 204) {
isPlaying = false;
return fallbackToLastPlayed
? { isPlaying, ...(await this.getLastPlayed())[0]}
? { isPlaying, ...(await this.getLastPlayed())[0] }
: null;
}
const responseData = (await response.json()) as CurrentlyPlaying;
Expand All @@ -96,13 +95,10 @@ export class SpotifyClient {

getLastPlayed = async (limit: number = 1): Promise<ResponseTrack[]> => {
try {

if(this.accessToken === null)
this.accessToken = await this._genAccesToken();

if(limit > 50 || limit < 1)
throw new Error('Limit must be between 1 and 50');

if (this.accessToken === null) this.accessToken = await this._genAccesToken();

if (limit > 50 || limit < 1) throw new Error('Limit must be between 1 and 50');

const headers = { Authorization: `Bearer ${this.accessToken}` };
const response = await fetch(`${LAST_PLAYED_URL}?limit=${limit}`, { headers });

Expand All @@ -113,9 +109,9 @@ export class SpotifyClient {

// TODO: add types once spotify-types is updated
const responseData = (await response.json()) as any;
const lastPlayedTrack = responseData.items.map((item: { track: Track; }) => {
const lastPlayedTrack = responseData.items.map((item: { track: Track }) => {
return filterResponse(item.track);
})
});

return lastPlayedTrack;
} catch (error: any) {
Expand Down
20 changes: 12 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,19 @@
"prepare": "husky install"
},
"devDependencies": {
"@types/node": "^17.0.21",
"ava": "^4.0.1",
"@types/node": "^17.0.23",
"ava": "^4.1.0",
"dotenv": "^16.0.0",
"husky": "^7.0.4",
"prettier": "^2.5.1",
"lint-staged": ">=10",
"prettier": "^2.6.1",
"spotify-types": "^1.0.5",
"ts-node": "^10.5.0",
"tsup": "^5.11.13",
"typescript": "^4.5.5"
"ts-node": "^10.7.0",
"tsup": "^5.12.2",
"typescript": "^4.6.3"
},
"dependencies": {
"node-fetch": "^3.2.2"
"node-fetch": "^3.2.3"
},
"ava": {
"extensions": {
Expand All @@ -53,5 +54,8 @@
"spotify-typescript",
"spotify-current-song",
"spotify-last-played-song"
]
],
"lint-staged": {
"*.{js,ts,md}": "prettier --write"
}
}
42 changes: 9 additions & 33 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

A simple node wrapper around the [Spotify web api](https://developer.spotify.com/documentation/web-api/) that exposes some useful methods like easily getting your currently playing track, last played track or both.

> I have been using a rough version of this lib in my [portfolio's spotify widget](https://www.rocktimsaikia.com/) from the very begining, so finally decided to turn it into a proper npm module.
> I have been using a rough version of this lib in my [portfolio](https://www.rocktimsaikia.com/) from the very begining, so finally decided to turn it into a proper npm module.
<br/>

Expand All @@ -28,7 +28,7 @@ const spotify = new SpotifyClient({
refreshToken: '<YOUR-SPOTIFY-REFRESH-TOKEN>'
});

// Get the currently playing track,(if there is no track playing, it will return null)
// Get the currently playing track,(if there is no track playing, it will return the last played track)
const currentlyPlayingTrack = await spotify.getCurrentlyPlaying();
/**
{
Expand All @@ -52,7 +52,7 @@ const lastPlayedTrack = await spotify.getLastPlayed();
*/

// To get a specific number of the recently played songs, just pass it to the method (1 < n < 50), default is 1
const recentTracks = await spotify.getLastPlayed(2)
const recentTracks = await spotify.getLastPlayed(2);
/**
[
{
Expand All @@ -67,54 +67,30 @@ const recentTracks = await spotify.getLastPlayed(2)
}
]
*/

// // If there is no track playing, this will return the last played song, to prevent this feature pass `fallbackToLastPlayed: false`
const currentTrack = await spotify.getCurrentlyPlaying({
fallbackToLastPlayed: true
});
/**
{
isPlaying: false,
title: '<track title>',
artist: '<artist name>',
album: '<album name>',
}
*/


```

<br/>

## API

### `SpotifyClient`
The exported class that needs to be instanciated to interact with the exposed APIs.

The exported class that needs to be instanciated to interact with the exposed APIs.

### `getCurrentlyPlaying`

Returns your currently playing track, if none returns null.

**Options**:
`fallbackToLastPlayed`: (default: false) If true, it will return the last played track if there is no currently playing track
`fallbackToLastPlayed`: (default: true) returns the last played track if there is no currently playing track, setting it to `false` will return null

### `getLastPlayed`

Returns your last played track. But can be used to get a list of your recently played tracks; accepts an optional integer as argument to get your desired number of recently played tracks. (default: 1) (limit is 1<n<50 )

## Development

Fork this repo and run

```sh
yarn install
```

or

```sh
npm install
```

Once the required packages are installed, create a `.env` file with the properties of `.env.example`.
Create a `.env` file with the properties of `.env.example`.
To run the tests, you will need to generate a `refresh_token` with the minium of the following spotify api scopes: `user-read-currently-playing`, `user-read-recently-played`.

## License
Expand Down

0 comments on commit f43e1fb

Please sign in to comment.