SPRINT 3 ‐ Backend Typescript - BlueJayBird11/UniJet GitHub Wiki

One of the goals at the start of this sprint was to convert the backend from javascript to typescript. It took a little longer than I would like to admit, but here is a summary of what's important.

Run

To start the app, make sure yarn is installed (there are other ways to run it, I just found convenient.

cd backend_ts
yarn build
yarn dev

App

The app is still and express.js server, just reorganized from the original server in it's own class.

Constructor

The constructor is where the layers of the service are added, so if a developer needs to add a service to the express app, then it should be added here:

constructor() {
  this.app = express();
  this.app.use(cors());
  this.app.use(express.json());
  this.routes();
}

Plugins

If a developer need to add a plugin, then it can done in the plugins function.

protected plugins(): void {
  this.app.use(express.json());
  this.app.use(express.urlencoded({ extended: true }));
}

Routing

Finally, if a developer needs to add a route to the server, then it should be done in a file and added to the routes function in the app:

protected routes(): void {
  this.app.route("/").get((req: Request, res: Response) => {
    res.send("welcome home");
  });
  this.app.use("/api/v1/passengers", PassengerRouter);
  this.app.use("/api/v1/classInfo", ClassInfoRouter);
  this.app.use("/api/v1/login", LoginRouter);
  this.app.use("/api/v1/forgotpassword", ForgotPassword);
}

Notice the format "api/v1/passengers". This is the route the frontend will call to use requests.

Routes

When making routes, they should be done in there own file.

Here is a sample of how the file should look before routes are added:

import BaseRoutes from "./base/BaseRouter";
import pool from "../db";

class DriverRoutes extends BaseRoutes {
  routes(): void {

  }
}

export default new DriverRoutes().router;

BaseRoutes is used for making the routes themselves, and the pool allows the server to connect directly to the Postgres database to run queries.

example

Here is an example of how both of these are used to get one passenger by their ID:

this.router.get("/:id", async (req, res) => {
  try {
    // console.log(req.params.id);
    const results = await pool.query(
      "SELECT * FROM passengers WHERE id = $1",
      [req.params.id]
    );
    res.status(200).json({
      status: "success",
      data: {
        passenger: results.rows[0],
      },
    });
  } catch (err) {
    console.log(err);
  }
});

Note that research should be done to send back responses with the correct status to the frontend.