SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 390 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express')
  2. const app = express()
  3. const Joi = require('@hapi/joi')
  4. const port = 5000
  5.  
  6. app.use(express.json())
  7.  
  8. //local database using arrays
  9. const users = []
  10.  
  11. const schema = Joi.object().keys({
  12.     firstname: Joi.string().alphanum().min(3).max(30).required(),
  13.     lastname: Joi.string().alphanum().min(3).max(30).required(),
  14.     email: Joi.string().email({ minDomainSegments: 2 }),
  15.     password: Joi.string().regex(/^[a-zA-Z0-9]{3,15}$/),
  16. })
  17.  
  18. app.post('/users', (req, res) => {
  19.     //check the type of user input
  20.     if (!req.is('application/json')) {
  21.         res.status(400).send({
  22.             status: 400,
  23.             error: "input can only be in json format"
  24.         })
  25.     }
  26.     else {
  27.         // json input from the user
  28.         const user = req.body
  29.  
  30.         // validation
  31.         const result = Joi.validate(user, schema)
  32.         if (result.error) {
  33.             res.status(400).send({
  34.                 status: 400,
  35.                 error: result.error.details[0].message
  36.             })
  37.         }
  38.         else {
  39.             // add user to our database if there are no errors
  40.             users.push(user)
  41.             res.status(200).send({
  42.                 status: 200,
  43.                 message: "user created successfully",
  44.                 data: user
  45.             })
  46.         }
  47.  
  48.     }
  49.  
  50.  
  51. })
  52.  
  53. app.get('/users', (req, res) => {
  54.     //get created user if validation passes
  55.     res.status(200).send({
  56.         status: 200,
  57.         message: "users fetched successfully",
  58.         data: users
  59.     })
  60.  
  61. })
  62.  
  63. app.listen(port, () => {
  64.     console.log(`app running on port ${port}`)
  65. })
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top