I am currently setting up an API in NextJS. In my /classes folder, I have index.js and [id].js files.
The purpose of /classes/ is to retrieve all classes from the database or add a new class. The purpose of /classes/[id] is to fetch a specific class, update it, or delete it. However, I am facing an issue where trying to get a class by id is returning all classes from the index.js file. Any suggestions on what might be missing?
index.js
if (req.method === 'GET') {
try {
console.log('in index get')
const allClasses = await db.collection('classes').orderBy('name').get()
const classes = allClasses.docs.map((doc) => {
return {
id: doc.id,
...doc.data()
}
})
res.status(200).json(classes)
} catch (error) {
res.status(400).json({
error: error.message
})
}
} else if (req.method === "POST") {
try {
await db.collection('classes').add({
...req.body,
lastUpdated: new Date().toISOString()
})
res.status(200).json({
message: 'New Class Created'
})
} catch (e) {
res.status(500).json({
error: 'There was an error adding class'
})
}
}
[id].js
switch (method) {
case 'GET':
try {
console.log('in id get')
const classById = await db.collection('classes').doc(id).get().data()
res.status(200).json(classById)
} catch (error) {
res.status(400).json({
error: `Class does not exist`
})
}
break;
case 'DELETE':
try {
await db.collection('classes').doc(id).delete()
res.status(200).json({
message: 'Class Deleted Successfully'
})
} catch (error) {
res.status(400).json({
error: `Class does not exist`
})
}
break;
case 'PUT':
try {
await db.collection('classes').doc(id).update({
...req.body,
lastUpdated: new Date().toISOString()
})
res.status(200).json({
message: 'Class Updated Successfully'
})
} catch (error) {
res.status(400).json({
error: `Class does not exist`
})
}
break;
default:
res.setHeader('Allow', ['GET', 'PUT', 'DELETE'])
res.status(405).end(`Method ${method} Not Allowed`)
break;
}