Friday, June 10, 2022

Destructuring Object Exports in NodeJS


Exporting three functions from a Javascript file:
search.js
function searchRecipes(searchTerm, recipesArray) {
}

function findByName(name, recipesArray) {
}

function findById(recipeid, recipesArray) {
}

// If it's an array, it uses position
// If it's an object, uses property name
// Exporting an object literal with three properties:
module.exports = { searchRecipes, findByName, findById };

The 'require' returns the exported object literal. Pull out two properties that we need to access in this file. The order does not matter. The property names determine the values that are assigned. These are two of the functions that we exported from search.js.

services/recipeservice.js
const { searchRecipes, findByName } = require('../search');

const RecipeService = {
    search(searchStr) {
      return searchRecipes(searchStr, recipesArray);
    },
    findrecipebyID(id) {
       let one_recipe = findById(id, recipeArray);
       return one_recipe;
    }
};

const MongoService = {
    add(recipeObject) {
    },
    search(searchTerm) {
    }
};

// Exporting an object literal with two properties:
module.exports = { RecipeService, MongoService };

Two different ways to pull out a particular property and assign to a different name:
controllers/recipecontroller.js
// 1.
const RecipeService = 
require('../services/recipeservice').MongoService;

// 2.
// Same as above but using destructuring.  
// The colon syntax lets us assign to a different name 
// than the property name:
const { RecipeService : MongoService } = 
require('../services/recipeservice');


Image: Jonny Gios, CC-BY-SA 3.0

Post a Comment

Note: Only a member of this blog may post a comment.