Sora952

Post/put detaille wild quest

Jun 5th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // dotenv loads parameters (port and database config) from .env
  2. require('dotenv').config();
  3. const express = require('express');
  4. const bodyParser = require('body-parser');
  5. const { check, validationResult } = require('express-validator');
  6. const connection = require('./db');
  7.  
  8. const app = express();
  9. app.use(bodyParser.json());
  10. app.use(bodyParser.urlencoded({ extended: false }));
  11.  
  12. // respond to requests on `/api/users`
  13. app.get('/api/users', (req, res) => {
  14.   // send an SQL query to get all users
  15.   connection.query('SELECT * FROM user', (err, results) => {
  16.     if (err) {
  17.       // If an error has occurred, then the client is informed of the error
  18.       res.status(500).json({
  19.         error: err.message,
  20.         sql: err.sql,
  21.       });
  22.     } else {
  23.       // If everything went well, we send the result of the SQL query as JSON
  24.       res.json(results);
  25.     }
  26.   });
  27. });
  28.  
  29. const userValidationMiddlewares = [
  30.   // email must be valid
  31.   check('email').isEmail(),
  32.   // password must be at least 8 chars long
  33.   check('password').isLength({ min: 8 }),
  34.   // let's assume a name should be 2 chars long
  35.   check('name').isLength({ min: 2 }),
  36. ];
  37.  
  38. app.post(
  39.   '/api/users',
  40.   userValidationMiddlewares,
  41.   (req, res) => {
  42.     const errors = validationResult(req);
  43.     if (!errors.isEmpty()) {
  44.       return res.status(422).json({ errors: errors.array() });
  45.     }
  46.     // send an SQL query to get all users
  47.     return connection.query('INSERT INTO user SET ?', req.body, (err, results) => {
  48.       if (err) {
  49.         // If an error has occurred, then the client is informed of the error
  50.         return res.status(500).json({
  51.           error: err.message,
  52.           sql: err.sql,
  53.         });
  54.       }
  55.       // We use the insertId attribute of results to build the WHERE clause
  56.       return connection.query('SELECT * FROM user WHERE id = ?', results.insertId, (err2, records) => {
  57.         if (err2) {
  58.           return res.status(500).json({
  59.             error: err2.message,
  60.             sql: err2.sql,
  61.           });
  62.         }
  63.         // If all went well, records is an array, from which we use the 1st item
  64.         const insertedUser = records[0];
  65.         // Extract all the fields *but* password as a new object (user)
  66.         const { password, ...user } = insertedUser;
  67.         // Get the host + port (localhost:3000) from the request headers
  68.         const host = req.get('host');
  69.         // Compute the full location, e.g. http://localhost:3000/api/users/132
  70.         // This will help the client know where the new resource can be found!
  71.         const location = `http://${host}${req.url}/${user.id}`;
  72.         return res
  73.           .status(201)
  74.           .set('Location', location)
  75.           .json(user);
  76.       });
  77.     });
  78.   },
  79. );
  80.  
  81. app.put(
  82.   '/api/users/:id',
  83.   userValidationMiddlewares,
  84.   (req, res) => {
  85.     const errors = validationResult(req);
  86.     if (!errors.isEmpty()) {
  87.       return res.status(422).json({ errors: errors.array() });
  88.     }
  89.     // send an SQL query to get all users
  90.     return connection.query('UPDATE user SET ? WHERE id = ?', [req.body, req.params.id], (err, results) => {
  91.       if (err) {
  92.         // If an error has occurred, then the client is informed of the error
  93.         return res.status(500).json({
  94.           error: err.message,
  95.           sql: err.sql,
  96.         });
  97.       }
  98.       // We use the insertId attribute of results to build the WHERE clause
  99.       return connection.query('SELECT * FROM user WHERE id = ?', req.params.id, (err2, records) => {
  100.         if (err2) {
  101.           return res.status(500).json({
  102.             error: err2.message,
  103.             sql: err2.sql,
  104.           });
  105.         }
  106.         // If all went well, records is an array, from which we use the 1st item
  107.         const insertedUser = records[0];
  108.         // Extract all the fields *but* password as a new object (user)
  109.         const { password, ...user } = insertedUser;
  110.         // Get the host + port (localhost:3000) from the request headers
  111.         const host = req.get('host');
  112.         // Compute the full location, e.g. http://localhost:3000/api/users/132
  113.         // This will help the client know where the new resource can be found!
  114.         const location = `http://${host}${req.url}/${user.id}`;
  115.         return res
  116.           .status(200)
  117.           .set('Location', location)
  118.           .json(user);
  119.       });
  120.     });
  121.   },
  122. );
  123.  
  124. app.listen(process.env.PORT, (err) => {
  125.   if (err) {
  126.     throw new Error('Something bad happened...');
  127.   }
  128.  
  129.   console.log(`Server is listening on ${process.env.PORT}`);
  130. });
Add Comment
Please, Sign In to add comment