I'm setting up an API in NextJS. Currently, I have a folder of routes /classes. In this folder, I have index.js and [id].js. 1
The purpose of /classes/ is to get all the classes in the db or post a new class. The purpose of /classes/[id] is to get the specific class, edit the class, or delete it. My issue is that when I try to get a class by id, its returning all the classes from the index.js file. Any ideas about what I'm 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;
}
CodePudding user response:
From your comment
{{localhost}}/api/classes/?id=DSGY9jjuY43M210uFg1U
Try doing this instead:
{{localhost}}/api/classes/DSGY9jjuY43M210uFg1U