mirror of
https://github.com/20kaushik02/spotify-manager.git
synced 2025-12-06 10:54:07 +00:00
62 lines
1.5 KiB
TypeScript
62 lines
1.5 KiB
TypeScript
import {
|
|
getCurrentUsersPlaylistsFirstPage,
|
|
getCurrentUsersPlaylistsNextPage,
|
|
} from "../api/spotify.ts";
|
|
|
|
import type { RequestHandler } from "express";
|
|
import type {
|
|
Pagination,
|
|
SimplifiedPlaylistObject,
|
|
} from "spotify_manager/index.d.ts";
|
|
|
|
import logger from "../utils/logger.ts";
|
|
|
|
/**
|
|
* Get user's playlists
|
|
*/
|
|
const fetchUserPlaylists: RequestHandler = async (req, res) => {
|
|
try {
|
|
const { authHeaders } = req.session;
|
|
if (!authHeaders)
|
|
throw new ReferenceError("session does not have auth headers");
|
|
// get first 50
|
|
const { resp } = await getCurrentUsersPlaylistsFirstPage({
|
|
res,
|
|
authHeaders,
|
|
});
|
|
if (!resp) return null;
|
|
|
|
const userPlaylists: Pick<
|
|
Pagination<SimplifiedPlaylistObject>,
|
|
"items" | "total"
|
|
> = {
|
|
items: [...resp.data.items],
|
|
total: resp.data.total,
|
|
};
|
|
let nextURL = resp.data.next;
|
|
// keep getting batches of 50 till exhausted
|
|
while (nextURL) {
|
|
const { resp } = await getCurrentUsersPlaylistsNextPage({
|
|
authHeaders,
|
|
res,
|
|
nextURL,
|
|
});
|
|
if (!resp) return null;
|
|
const nextData = resp.data;
|
|
|
|
userPlaylists.items.push(...nextData.items);
|
|
nextURL = nextData.next;
|
|
}
|
|
|
|
res.status(200).send(userPlaylists);
|
|
logger.debug("Fetched user playlists", { num: userPlaylists.total });
|
|
return null;
|
|
} catch (error) {
|
|
res.status(500).send({ message: "Internal Server Error" });
|
|
logger.error("fetchUserPlaylists", { error });
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export { fetchUserPlaylists };
|