Skip to content

Ramer8/Mobility-API-Backend

Repository files navigation

Mobility App Backend


Mobility App

Thank you very much for your interest in my project. It's the last proyect, a complete full stack project with Geekshubs Academy of the Full Stack Development Bootcamp 🚀.


GITHUBDOCKERMYSQLNodeExpressjsJWT

Contents 🗂️
  1. Full Description
  2. Data Base diagram
  3. Tasks
  4. Instalation & Develop
  5. Author / Contact
It an app to hire a service to transport people from one place to another paying a price for it..
Full Description 📝
    Users can register for the application, log in and access it. They can search for a destination, choose from different types of cars and make the trip. A driver responds to the request and picks up the passenger. Once the trip is completed, they can rate the driver. Users must complete their profile and choose the payment method. They can also access their trip history.
Data Base Diagram

Tasks 📝

  • Create a Data Base
  • Migrations & Seeders for all tables.
  • Endpoints
  • View endopints

        Authentication

    1. Register Users
    2. POST localhost:5500/auth/register

    3. Login
    4. POST https://localhost:5500/auth/login


    5. Register Drivers
    6. POST localhost:5500/auth/drivers/register

    7. Login
    8. POST localhost:5500/auth/drivers/login


        Users

    9. Get All Users with pagination
    10. GET http://localhost:5500/users


    11. Pagination example
    12. "url_example_of_pagination":"http://localhost:5500/users?page=2",

      "url_example_of_pagination1":"http://localhost:5500/users?limit=20",

      "url_example_of_pagination2":"http://localhost:5500/users?page=3&limit=15"


    13. Get User Profile
    14. GET http://localhost:5500/users/profile


    15. Update User Profile
    16. PUT http://localhost:5500/users/profile

      { "userName": "Jhon Smith", "phone": "+3461371436", "address": "carrer xativa 20", "payment": "credit" }


    17. Delete User by Id
    18. DELETE http://localhost:5500/users/:id


    19. Delete one User or more by Id arrays (superAdmin)
    20. DELETE http://localhost:5500/users

      { "usersId" : [4,5,7,5,78,2] }

      { "usersId" : [12] }


    21. Get Users with search by query
    22. GET http://localhost:5500/users/search?search=email

      GET http://localhost:5500/users/search?search=name


    23. Create Trip
    24. POST http://localhost:5500/trips/

      { "startLocation": "[39.5102451,-0.4115579]", "destination": "Valencia, Spain", "driverId": 3 }


    25. Get all Trips (Super_admin)
    26. GET http://localhost:5500/trips/all


    27. Get my all Trips (TOKEN)
    28. PUT http://localhost:5500/trips/:id


    29. Get trips by Id (TOKEN)
    30. GET http://localhost:5500/trips


    31. Update Trip (TOKEN)
    32. PUT http://localhost:5500/trips/

      { "tripDate": "2024-05-01 19:00:00", "trip_id": 23, "driverId": 4, "startLocation": "Godella", "destination":"Palau de Congresos", "carId":2 }


    33. Update Trip by Id (TOKEN)
    34. PUT http://localhost:5500/trips/:id


    35. Delete Trip by Id (TOKEN)
    36. DELETE http://localhost:5500/trips/:id


    37. Delete more than one Trips by Id array (superAdmin)
    38. DELETE http://localhost:5500/trips

      { "tripsId" : [4,2,5,6,8,10] }

      { "tripsId" : [6] }


    39. Get All Drivers with pagination
    40. GET http://localhost:5500/drivers


    41. Pagination Example
    42. url_example_of_pagination":"http://localhost:5500/drivers?page=2

      "url_example_of_pagination1":"http://localhost:5500/drivers?limit=20",

      "url_example_of_pagination2":"http://localhost:5500/drivers?page=3&limit=15"


    43. Get Driver Profile
    44. GET http://localhost:5500/drivers/profile


    45. Update Driver Profile
    46. PUT http://localhost:5500/drivers/profile


    47. Delete Driver by Id
    48. DELETE http://localhost:5500/drivers/:id


    49. Delete one Driver or more by Id arrays (superAdmin)
    50. DELETE http://localhost:5500/drivers

      { "driversId" : [4,5,7,5,78,2] }

      { "driversId" : [12] }


      All non-public endpoints with corresponding middlewares

        We can find here the collection of all endpoints in Thunder Client: You have to open Thunder Client Go to collections Import this file:

      ./HTTP/thunder-collection_TAXI APP.json



    Instalation & Develop ⛏️

      1. INSTALL DOCKER

      DOCKER

      1. Install docker and run this command to get a container
      2. $ docker run --name mysql-exampleName -p 3309:3306 -e MYSQL_ROOT_PASSWORD=1234 -d mysql

      3. Example
      4. $ mysql -h localhost -P 3306 -u root -p you will need -h (host), -P (port), -u(username) and -p (password)

      2. INSTALL EXPRESS

      Express

        $ npm init

      1. Run follow command to create "package-lock.json" install node_modules
      2. $ npm install express --save

      3. Create .gitignore in root and add "./node_modules" , ".env" and ".dist" to avoid upload to github repository
      4. $ npm install typescript -D

      5. Create the 'tsconfig.json' file
      6. $ npx tsc --init

      7. Install types/express & node
      8. $ npm install @types/express @types/node -D

      9. Install dependencies to compile TS (nodemon)
      10. $ npm install ts-node nodemon -D

      11. Create ".env" and ".env.example" file The .env file has the key & value credentials to access to the data base. It should not be visible, for this reason we add it to .gitingnore. The ".env.example" files have the same structure to build your ".env" file on your local
      12. Put the follow keys in .env file.
      13. PORT =4XXX
        
        #conexion a bd
        DB_USER=root
        DB_PASSWORD=XXXX
        DB_PORT=33XX
        DB_HOST=localhost
        DB_DATABASE=dataBaseName
        
        # JWT
        
        JWT_SECRET=xxxxxx

      14. Install 'dotenv' to added th depencencies and will grab data from the .env file
      15. $ npm install dotenv

      16. DOTENV - Create the folder "src" with "server.ts" file inside. This the code to connect to the server.
      17. import "dotenv/config"
        
        import { app } from "./app"
        import { AppDataSource } from "./database/db"
        
        const PORT = process.env.PORT || 5500
        
        const startServer = () => {
          AppDataSource.initialize()
            .then(() => {
              console.log("database connected")
              app.listen(PORT, () => {
                console.log(`Server is running on port: ${PORT}`)
              })
            })
            .catch((error: any) => {
              console.log("error")
            })
        }
        
        startServer()
      18. We create app.ts file
      19. // links to .env file
        import express, { Application } from "express"
        import "dotenv/config"
        import { authRouter } from "./routes/authRoutes"
        
        // export app function export
        const app: Application = express()
        // parses response to .json
        app.use(express.json())
        // testing request
        app.get("/healthy", (req, res) => {
          res.status(200).json({
            success: true,
            message: "Server is healthy",
          })
        })
        // auth Users & Drivers
        app.use("/", authRouter) //<-- Route Example
      3. CREATE MYSQL

      MYSQL

      1. Think and rethink the database, avoid redundancy between keys and related tables. Identify primary keys (PK) and foreign keys (FK). Choose the type of value, if it is 'NULL' (not required) or can be 'UNIQUE' fields.
      2. Open Mysql Workbench and set up new dataBase connection
      3. $ npm run dev


      4. MIGRATIONS & MODELS
      • Creating MIGRATIONS [Data Definition Language (DDL): with typeorm]: $ npm run run-migrations ./src/database/migrations

      • It's possible that's need populate with one basic table before continue with the migrations go to the point 11.Run Project
      • Adding them to DataSource.migrations in the db.ts file: Role, User, Driver, Trip, Car, Brand

      • Creating MODELS (entities) [Data Manipulation Language (DML)]

      • Adding them to DataSource.entities in the db.ts file: Roles, Users, Drivers, Trips, Cars, Brands

      5. CONTROLLERS
      • We create controllers (in a folder on the same level with package.json): > auth, users, drivers, trips
      6. ROUTES
      • We create routes (in app.ts) for CRUD (create, read, update and delete) database records for users ,drivers, trips.
      7. MIDDLEWARE: auth( )
      • Additionally we need to control access to our data. We will use 'middleware' functions.
      • Auth(authorization system based on TOKENs) will block anything that should not be seen by the general public. In our case, it only does not affectregister, loginandgetServices` (since those are the endpoints accessible without logging in).
      • The auth() function verifies an encrypted TOKEN created automatically at login. With an active token we have access to other data.
      8. MIDDLEWARE: isSuperAdmin()
      • We also want to grant special administrative access. With another middleware, the isSuperAdmin() function, we control PERMISSIONS.
      • The 'superadmin' role would be able to reach all data, while Users would have a more limited reach. More levels can be implemented
      9. TOKENDATA
      • For the TOKEN to work, we create a new file ./types/index.d.ts with the following lines: We must add driverId, because in this project we have auth users and auth drivers, and we need both to use tokenData.

        export type TokenData = {
        driverId: number
        userId: number
        roleName: string
        }
        declare global {
        namespace Express {
        export interface Request {
        tokenData: TokenData
        }
        }
        }
      10. SEEDERS
      • In order to check out this project, you'll need to populate the database. We create a seeders.ts file, we use the npm faker library to create fake users, cars and drivers.

      $ npm run seed

      11. RUN PROJECT
      1. Clone this repository
      2. Run in terminal
      3. $ npm install

      4. Conect repository with database
      5. Run migrations:
      6. $ npm run run-migrations

      7. Run seeders:
      8. $ npm run seeders

      9. Start server:
      10. $ npm run dev


    1. - super_admin & random user - Credentials
    2. 
      {
      "first_name": "Super",
      "last_name": "Super"
      "email": "[email protected]"
      "password": 123456,
      "role_id": 3
      }
      
      {
      "first_name": "user",
      "last_name": "user"
      "email": "[email protected]"
      "password": 123456,
      "role_id": 1
      }
      
      

      Deployment

      The next steps is deploy the full proyect


    Author

    About

    No description, website, or topics provided.

    Resources

    Stars

    Watchers

    Forks

    Releases

    No releases published

    Packages

    No packages published