Categories
JavaScript Answers

How to add a catch all route for everything except for /login with Node.js Express?

To add a catch all route for everything except for /login with Node.js Express, we add the route for /login before adding the catch all route.

For instance, we write

app.get("/login", (req, res) => {
  //...
});

app.get("/", (req, res) => {
  //...
});

app.get("*", (req, res) => {
  //...
});

to add get routes for the /login and / URLs before adding the catch all route to let the higher route handlers handle requests to /login and /.

Categories
JavaScript Answers

How to avoid type errors on mocked functions with TypeScript and Jest?

To avoid type errors on mocked functions with TypeScript and Jest, we use the typeof operator.

For instance, we write

import myModuleThatCallsAxios from "../myModule";
import axios from "axios";

jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;

it("Calls the GET method as expected", async () => {
  const expectedResult: string = "result";

  mockedAxios.get.mockReturnValueOnce({ data: expectedResult });
  const result = await myModuleThatCallsAxios.makeGetRequest();

  expect(mockedAxios.get).toHaveBeenCalled();
  expect(result).toBe(expectedResult);
});

to cast the type of mockedAxios and axios to jest.Mocked<typeof axios>.

jest.Mocked is the generic type for mocked objects.

typeof axios gets the type of the axios object automatically.

Categories
JavaScript Answers

How to update document by _id with Node.js node-mongodb-native?

To select document by _id with Node.js node-mongodb-native, we call the update method.

For instance, we write

const mongo = require("mongodb");
const id = new mongo.ObjectID(theId);
collection.update({ _id: id });

to create an object ID object with the ObjectID constructor.

And then we call update to update the document in the collection with the id _id value.

Categories
JavaScript Answers

How to redirect user’s browser URL to a different page in Node.js?

To redirect user’s browser URL to a different page in Node.js, we call the Express res.redirect method.

For instance, we write

const express = require("express");
const app = express();

app.get("*", (req, res) => {
  res.redirect("https://www.example.com/");
});

app.set("port", process.env.PORT || 3000);
const server = app.listen(app.get("port"), () => {});

to call res.redirect to redirect to https://www.example.com in the catch get route we created.

Categories
JavaScript Answers

How to get the time of day in JavaScript or Node.js?

To get the time of day in JavaScript or Node.js, we use the date’s getHour method.

For instance, we write

const date = new Date();
const currentHour = date.getHours();

to create a date object with the current date and time with the Date constructor.

And then we call getHours on it to get the current hour of the day.