From 7ff52218a8c70c3fb403f033fda35b6d39bba983 Mon Sep 17 00:00:00 2001 From: maciejpedzich Date: Wed, 29 Jun 2022 20:38:10 +0200 Subject: [PATCH] Create a server route for getting snapshot entries --- .../api/playlists/[playlistId]/snapshots.ts | 55 +++++++++++++++++++ server/utils/filterByUniqueKeyValue.ts | 3 + 2 files changed, 58 insertions(+) create mode 100644 server/api/playlists/[playlistId]/snapshots.ts create mode 100644 server/utils/filterByUniqueKeyValue.ts diff --git a/server/api/playlists/[playlistId]/snapshots.ts b/server/api/playlists/[playlistId]/snapshots.ts new file mode 100644 index 0000000..23d0f48 --- /dev/null +++ b/server/api/playlists/[playlistId]/snapshots.ts @@ -0,0 +1,55 @@ +import { $fetch } from 'ohmyfetch'; + +import { octokit } from '~~/server/utils/octokit'; +import { filterByUniqueKeyValue } from '~~/server/utils/filterByUniqueKeyValue'; + +export default defineEventHandler(async (event) => { + const query = useQuery(event); + const sinceDateParam = (query.sinceDate as unknown as string) || '2021-12-01'; + const untilDateParam = + (query.untilDate as unknown as string) || new Date().toISOString(); + const DECEMBER_1ST_2021_TIMESTAMP = 16383168e5; + + const since = new Date( + Math.max(Date.parse(sinceDateParam), DECEMBER_1ST_2021_TIMESTAMP) + ).toISOString(); + + const until = new Date( + Math.min(Date.parse(untilDateParam), Date.now()) + ).toISOString(); + + const playlistId = event.context.params.playlistId; + const { data: commitListings } = await octokit.rest.repos.listCommits({ + owner: 'mackorone', + repo: 'spotify-playlist-archive', + author: 'github-actions[bot]@users.noreply.github.com', + path: `playlists/pretty/${playlistId}.json`, + since, + until + }); + + if (commitListings.length === 0) + throw new Error('There are no archive entries of this playlist'); + + const snapshotFileContents = await Promise.all( + commitListings.map(({ sha }) => + $fetch<{ snapshot_id: string }>( + `https://raw.githubusercontent.com/mackorone/spotify-playlist-archive/${sha}/playlists/pretty/${playlistId}.json`, + { parseResponse: JSON.parse } + ) + ) + ); + const possiblyDuplicateSnapshotEntries = snapshotFileContents.map( + ({ snapshot_id }, index) => ({ + snapshot_id, + commit_sha: commitListings[index].sha, + date_captured: commitListings[index].commit.author.date + }) + ); + const uniqueSnapshotEntries = filterByUniqueKeyValue( + possiblyDuplicateSnapshotEntries, + 'snapshot_id' + ); + + return uniqueSnapshotEntries; +}); diff --git a/server/utils/filterByUniqueKeyValue.ts b/server/utils/filterByUniqueKeyValue.ts new file mode 100644 index 0000000..dbd35c8 --- /dev/null +++ b/server/utils/filterByUniqueKeyValue.ts @@ -0,0 +1,3 @@ +export function filterByUniqueKeyValue(items: T[], key: keyof T) { + return [...new Map(items.map((item) => [item[key], item])).values()]; +}