const express = require('express'); const bodyParser = require('body-parser'); const models = require('./models'); import * as api from '../client/src/api'; const app = express(); // TODO: configurable port const port = process.env.PORT || 5000; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.post(api.CreateSongEndpoint, (req: any, res: any) => { if (!api.checkCreateSongRequest(req)) { console.log('Invalid CreateSong request: ' + JSON.stringify(req.body)); res.sendStatus(400); return; } const reqObject: api.CreateSongRequest = req.body; console.log("Request create song: ", reqObject); // TODO: remove // First check that the artist exists. models.Artist.findAll({ where: { id: reqObject.artistId } }) .then((artist: any[]) => { if (artist.length != 1) { console.log('Invalid CreateSong request: ' + JSON.stringify(req.body) + ". There is no artist with id " + reqObject.artistId + "."); res.sendStatus(400); return; } const song = models.Song.create({ title: reqObject.title, ArtistId: reqObject.artistId }); const responseObject: api.CreateSongResponse = { id: song.id }; res.status(200).send(responseObject); }) }); app.get(api.ListSongsEndpoint, (req: any, res: any) => { if (!api.checkListSongsRequest(req)) { console.log('Invalid ListSongs request: ' + JSON.stringify(req.body)); res.sendStatus(400); return; } models.Song.findAll({ include: [models.Artist] }) .then((songs: any[]) => { console.log(songs); const response: api.ListSongsResponse = songs.map((song: any) => { return { title: song.title, id: song.id, artistName: song.Artist.name, artistId: song.ArtistId, }; }); res.send(response); }); }); app.post(api.CreateArtistEndpoint, (req: any, res: any) => { if (!api.checkCreateArtistRequest(req)) { console.log('Invalid CreateArtist request: ' + JSON.stringify(req.body)); res.sendStatus(400); return; } const reqObject: api.CreateArtistRequest = req.body; const artist = models.Artist.create(reqObject); const responseObject: api.CreateArtistResponse = { id: artist.id }; res.status(200).send(responseObject); }); app.get(api.ListArtistsEndpoint, (req: any, res: any) => { if (!api.checkListArtistsRequest(req)) { console.log('Invalid ListArtists request: ' + JSON.stringify(req.body)); res.sendStatus(400); return; } models.Artist.findAll() .then((artists: any[]) => { const response: api.ListArtistsResponse = artists.map((artist: any) => { return { name: artist.name, id: artist.id, }; }); res.send(response); }); }); models.sequelize.sync().then(() => { app.listen(port, () => console.log(`Listening on port ${port}`)); }) export { }