Skip to content

Instantly share code, notes, and snippets.

@skolhustick
Created August 10, 2021 10:38
Show Gist options
  • Save skolhustick/d649247628cfef2e57ca9a63ec1cd1cf to your computer and use it in GitHub Desktop.
Save skolhustick/d649247628cfef2e57ca9a63ec1cd1cf to your computer and use it in GitHub Desktop.
// api/users.js
import dbConnect from '../../lib/dbConnect'
import User from '../../models/User'
export default async function handler (req, res) {
const { method } = req
await dbConnect()
switch (method) {
case 'GET':
try {
const users = await User.find({})
res.status(200).json({ success: true, data: users })
} catch (error) {
res.status(400).json({ success: false })
}
break
case 'POST':
try {
const user = await User.create(req.body)
res.status(201).json({ success: true, data: user })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment