From cb79628733d6422f7027ccb537866a18b5f499fe Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Thu, 1 Aug 2024 01:31:17 -0700 Subject: [PATCH] Add support for recent PSN games --- src/routes/api/psn/+server.ts | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/routes/api/psn/+server.ts diff --git a/src/routes/api/psn/+server.ts b/src/routes/api/psn/+server.ts new file mode 100644 index 0000000..1bfddd9 --- /dev/null +++ b/src/routes/api/psn/+server.ts @@ -0,0 +1,42 @@ +import 'dotenv/config' +import type { AuthTokensResponse, RecentlyPlayedGamesResponse } from 'psn-api' +import type { RequestHandler } from './$types' + +import Module from 'node:module' +const require = Module.createRequire(import.meta.url) +const { + exchangeNpssoForCode, + exchangeCodeForAccessToken, + getRecentlyPlayedGames +} = require('psn-api') + +const PSN_NPSSO_TOKEN = process.env.PSN_NPSSO_TOKEN + +export const GET: RequestHandler = async ({ url }) => { + let authorization = await authorize(PSN_NPSSO_TOKEN || '') + + const response: RecentlyPlayedGamesResponse = await getRecentlyPlayedGames(authorization, { + limit: 5, + categories: ['ps4_game', 'ps5_native_game'] + }) + + const games: SerializableGameInfo[] = response.data.gameLibraryTitlesRetrieve.games.map( + (game) => ({ + id: game.productId, + name: game.name, + playtime: undefined, + lastPlayed: new Date(game.lastPlayedDateTime), + coverURL: game.image.url + }) + ) + + return new Response(JSON.stringify(games), { + headers: { 'Content-Type': 'application/json' } + }) +} + +async function authorize(npsso: string): Promise { + const accessCode = await exchangeNpssoForCode(npsso) + const authorization = await exchangeCodeForAccessToken(accessCode) + return authorization +}