populated album on get by id request

parent 9da4cf60
......@@ -32,28 +32,56 @@ const Album = model<IAlbum>(
);
router.get('/', async (req: Request, res: Response) => {
const albums = await Album.find().populate<{artist: IArtist}>('artist');
res.send(albums);
if (!req.query.artist) {
try {
const albums = await Album.find().populate<{artist: IArtist}>('artist');
res.send(albums);
return;
} catch (err: unknown) {
res.send('Could not get albums');
}
}
try {
const artistsAlbums = await Album.find({artist: req.query.artist});
res.send(artistsAlbums);
} catch (err: unknown) {
res.send(`Could not find albums of ${req.query.artist} `);
}
});
router.get('/:id', async (req: Request, res: Response) => {
try {
const album = await Album.findById(req.params.id).populate<{
artist: IArtist;
}>('artist');
res.send(album);
} catch (err: unknown) {
res.send('No such artist exists');
}
});
router.post(
'/',
upload.single('albumImage'),
async (req: Request, res: Response) => {
const album: HydratedDocument<IAlbum> = new Album({
name: req.body.name,
albumImage: {
data: fs.readFileSync(
path.join('uploads/albums/' + req.file?.filename)
),
contentType: 'image',
},
year: req.body.year,
artist: req.body.artist,
});
await album.save();
res.send('Sucessfully saved');
try {
const album: HydratedDocument<IAlbum> = new Album({
name: req.body.name,
albumImage: {
data: fs.readFileSync(
path.join('uploads/albums/' + req.file?.filename)
),
contentType: 'image',
},
year: req.body.year,
artist: req.body.artist,
});
await album.save();
res.send('Sucessfully saved');
} catch (err: unknown) {
res.send('Could not post album');
}
}
);
......
......@@ -31,27 +31,35 @@ const artistSchema = new Schema<IArtist>({
const Artist = model<IArtist>('Artist', artistSchema);
router.get('/', async (req: Request, res: Response) => {
const artists = await Artist.find();
res.send(artists);
try {
const artists = await Artist.find();
res.send(artists);
} catch (err: unknown) {
res.send('could not get artists');
}
});
router.post(
'/',
upload.single('image'),
async (req: Request, res: Response) => {
const artist: HydratedDocument<IArtist> = new Artist({
name: req.body.name,
description: req.body.description,
image: {
data: fs.readFileSync(
path.join('uploads/artists/' + req.file?.filename)
),
contentType: 'image',
},
});
await artist.save();
res.send('Sucessfully saved');
try {
const artist: HydratedDocument<IArtist> = new Artist({
name: req.body.name,
description: req.body.description,
image: {
data: fs.readFileSync(
path.join('uploads/artists/' + req.file?.filename)
),
contentType: 'image',
},
});
await artist.save();
res.send('Sucessfully saved');
} catch (err: unknown) {
res.send('Could not post');
}
}
);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment