Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Challenge starting point #26

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/* eslint-disable import/no-unresolved */
// dotenv loads parameters (port and database config) from .env
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator');
const connection = require('./db');

const app = express();
Expand All @@ -25,6 +27,93 @@ app.get('/api/users', (req, res) => {
});
});

const userValidationMiddlewares = [
// email must be valid
check('email').isEmail(),
// password must be at least 8 chars long
check('password').isLength({ min: 8 }),
// let's assume a name should be 2 chars long
check('name').isLength({ min: 2 }),
];

app.post(
'/api/users',
userValidationMiddlewares,
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// send an SQL query to get all users
return connection.query('INSERT INTO user SET ?', req.body, (err, results) => {
if (err) {
// If an error has occurred, then the client is informed of the error
return res.status(500).json({
error: err.message,
sql: err.sql,
});
}
// We use the insertId attribute of results to build the WHERE clause
return connection.query('SELECT * FROM user WHERE id = ?', results.insertId, (err2, records) => {
if (err2) {
return res.status(500).json({
error: err2.message,
sql: err2.sql,
});
}
// If all went well, records is an array, from which we use the 1st item
const insertedUser = records[0];
// Extract all the fields *but* password as a new object (user)
const { password, ...user } = insertedUser;
// Get the host + port (localhost:3000) from the request headers
const host = req.get('host');
// Compute the full location, e.g. http://localhost:3000/api/users/132
// This will help the client know where the new resource can be found!
const location = `http://${host}${req.url}/${user.id}`;
return res
.status(201)
.set('Location', location)
.json(user);
});
});
},
);

app.put(
'/api/users/:id',
userValidationMiddlewares,
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
return connection.query('UPDATE INTO user SET ?', req.body, (err, results) => {
if (err) {
return res.status(500).json({
error: err.message,
sql: err.sql,
});
}
return connection.query('SELECT * FROM user WHERE id = ?', results.req.params.id, (err2, records) => {
if (err2) {
return res.status(500).json({
error: err2.message,
sql: err2.sql,
});
}
const insertedUser = records[0];
const { password, ...user } = insertedUser;
const host = req.get('host');
const location = `http://${host}${req.url}/${user.id}`;
return res
.status(201)
.set('Location', location)
.json(user);
});
});
},
);

app.listen(process.env.PORT, (err) => {
if (err) {
throw new Error('Something bad happened...');
Expand Down
17 changes: 15 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.3.1",
"mysql": "^2.17.1"
},
"devDependencies": {
Expand Down