Categories
JavaScript Answers

How to determine if object exists AWS S3 Node.JS SDK?

To determine if object exists AWS S3 Node.JS SDK, we call the headObject method.

For instance, we write

AWS.config.update({
  accessKeyId: "*****",
  secretAccessKey: "****",
  region: region,
  version: "****",
});
const s3 = new AWS.S3();

const params = {
  Bucket: s3BucketName,
  Key: "filename",
};
try {
  await s3.headObject(params).promise();
  console.log("File Found in S3");
} catch (err) {
  console.log("File not Found ERROR : " + err.code);
}

to call headObject with the params with the bucket name and key to check if the object with the key exists in the Bucket.

And we call promise to make it return a promise.

If it doesn’t throw an error, then the object is found.

Categories
JavaScript Answers

How to check if /usr/local/bin is in $PATH on Mac?

To check if /usr/local/bin is in $PATH on Mac, we print the $PATH environment variable value.

To do this, we run

echo $PATH

and check if /usr/local/bin is included in the screen output.

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.