import { Application } from "express"; import { dbDelete, dbRead, dbStore } from "../database.js"; import createHttpError from "http-errors"; import generateID from "../idgen.js"; export default function playlists(app: Application) { app.get('/playlists/list', (req, res) => { const username = req.headers['x-username'] as string; const user = dbRead('users', username); res.send( user.playlists .map((pId: string) => dbRead('playlists', pId)) ); }); app.get('/playlists/:id', (req, res) => { const username = req.headers['x-username'] as string; const user = dbRead('users', username); if (!user.playlists.includes(req.params.id)) throw createHttpError[403](); res.send( dbRead('playlists', req.params.id) ); }); app.post('/playlists/new', (req, res) => { if (typeof req.body.name !== 'string') throw createHttpError[400](); const username = req.headers['x-username'] as string; const user = dbRead('users', username); const id = generateID(); user.playlists.push(id); dbStore('playlists', id, { id, owner: username, songs: [], name: req.body.name }); dbStore('users', username, user); res.send({ id }); }); app.delete('/playlists/:id', (req, res) => { const username = req.headers['x-username'] as string; const user = dbRead('users', username); if (!user.playlists.includes(req.params.id)) throw createHttpError[403](); user.playlists = user.playlists.filter((x: string) => x !== req.params.id); dbDelete('playlists', req.params.id); dbStore('users', username, user); res.send({ ok: true }); }); app.post('/playlists/:id', (req, res) => { if (typeof req.params.id !== 'string' || typeof req.body.songId !== 'string') throw createHttpError[400](); const username = req.headers['x-username'] as string; const user = dbRead('users', username); if (!user.playlists.includes(req.params.id)) throw createHttpError[404](); const playlist = dbRead('playlists', req.params.id); playlist.songs.push(req.body.songId); dbStore('playlists', req.params.id, playlist); res.send({ ok: true }); }); app.delete('/playlists/:id/:songId', (req, res) => { if (typeof req.params.id !== 'string' || typeof req.params.songId !== 'string') throw createHttpError[400](); const username = req.headers['x-username'] as string; const user = dbRead('users', username); if (!user.playlists.includes(req.params.id)) throw createHttpError[404](); const playlist = dbRead('playlists', req.params.id); playlist.songs = playlist.songs.filter((x: string) => x !== req.params.songId); dbStore('playlists', req.params.id, playlist); res.send({ ok: true }); }); }