Simples, porém diferente
É só uma questão de ler documentação e prestar atenção aos detalhes.
// Arquivo: src/index.js
import dotenv from 'dotenv';
import express from 'express';
import mongodbConnectMiddleware from './middlewares/mongodb.js';
import router from './routes.js';
.config();
dotenv
const app = express();
.use(express.json());
app.use(mongodbConnectMiddleware);
app.use(router);
app
const port = process.env.APP_PORT;
.listen(port, () => {
appconsole.log(`Listening on: http://localhost:${port}`);
; })
// Arquivo: src/routes.js
import { Router } from 'express';
import * as userController from './controllers/user.js';
const router = Router();
router.post('/users', userController.createUser)
.post('/users/login', userController.userLogin);
export default router;
// Arquivo: src/middlewares/mongodb.js
import mongo from 'mongodb';
async function mongodbConnectMiddleware(req, res, next) {
const client = new mongo.MongoClient(
process.env.MONGODB_CONNECTION
;
)
await client.connect();
.db = client.db(process.env.MONGODB_DATABASE);
reqnext();
}
export default mongodbConnectMiddleware;
// Arquivo: src/controllers/user.js
export async function createUser(req, res) {
const usersCollection = req.db.collection('users');
const user = await usersCollection.findOne({
username: req.body.username,
;
})
if (user) {
res.status(422)
.json({
'message': 'Username already exists!',
;
})
return;
}
const newUser = await usersCollection.insertOne({
username: req.body.username,
password: req.body.password,
;
})
res.status(201)
.json({
username: req.body.username,
;
})
}
export async function userLogin(req, res) {
const usersCollection = req.db.collection('users');
const user = await usersCollection.findOne({
username: req.body.username,
password: req.body.password,
;
})
if (!user) {
res.status(401)
.json({
message: 'Invalid credentials!',
;
})
return;
}
res.status(200)
.json({
message: 'Login successful!',
access_key: '...',
expires_in: '...',
;
}) }