added track router and model

parent ecb79a32
......@@ -4,6 +4,7 @@ import {artistRouter} from './routes/artist';
import cors from 'cors';
import {albumRouter} from './routes/albums';
import {connect} from 'mongoose';
import {trackRouter} from './routes/track';
const app: Express = express();
app.use(json());
......@@ -11,6 +12,7 @@ app.use(cors());
app.use('/artists', artistRouter);
app.use('/albums', albumRouter);
app.use('/tracks', trackRouter);
const run = async () => {
await connect(`${process.env.MONGO_URL}/musicApp`);
......
......@@ -8,7 +8,7 @@ import {IArtist} from './artist';
const upload = multer({dest: 'uploads/albums'});
const router = express.Router();
interface IAlbum {
export interface IAlbum {
name: string;
albumImage: File;
year: number;
......
import express, {Request, Response} from 'express';
import {model, Schema, HydratedDocument, Types} from 'mongoose';
import {IAlbum} from './albums';
const router = express.Router();
interface ITrack {
name: string;
album: Types.ObjectId;
duration: string;
}
const Track = model<ITrack>(
'Track',
new Schema({
name: String,
duration: String,
album: {
type: Schema.Types.ObjectId,
ref: 'Album',
},
})
);
router.get('/', async (req: Request, res: Response) => {
if (!req.query.album) {
try {
const tracks = await Track.find().populate<{album: IAlbum}>('album');
res.send(tracks);
return;
} catch (err: unknown) {
res.send('Could not get tracks');
}
}
try {
const albumTracks = await Track.find({album: req.query.album});
res.send(albumTracks);
} catch (err: unknown) {
res.send(`Could not find album tracks of ${req.query.album} `);
}
});
router.post('/', async (req: Request, res: Response) => {
try {
const track: HydratedDocument<ITrack> = new Track({
name: req.body.name,
album: req.body.album,
duration: req.body.duration,
});
await track.save();
res.send(`Saved track: ${track}`);
} catch (err: unknown) {
res.send('Could not create track');
}
});
export {router as trackRouter};
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