DEV Community

Sohail Jafri
Sohail Jafri

Posted on

Stay Ahead of the Game: Leverage Chokidar CLI to Maximize Your Coding Efficiency!

Image description

This article’ll explore a powerful setup that automates managing exports from multiple MongoDB models in your backend code. By leveraging a custom script and Chokidar CLI, you can eliminate the tedious task of manually updating the models/index.ts file whenever you add or modify your models. Let’s dive in!

Table of Contents

Introduction

Managing multiple MongoDB models can become cumbersome, especially when it comes to maintaining the index.ts file that exports them for better code readability and organization. Manually updating this file every time you add or modify a model can be time-consuming and error-prone.

This article outlines a solution that automates this process, allowing you to focus on writing code instead of managing exports.

Prerequisites

Before we get started, ensure you have the following:

  • Node.js installed on your machine
  • A working MongoDB instance (optional) as you just export anything
  • Basic knowledge of JavaScript and Node.js

Setting Up the Script

  1. Create a New Script: In your project directory, create a new script file (e.g., generateIndex.js).
  2. Extract Exports from Models: Write a function to read your model files and extract the necessary exports. Here’s a simple example:
import { fileURLToPath } from 'url'
import path, { dirname, join, resolve } from 'path'
import * as fs from 'fs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const modelsDir = resolve(__dirname, '../models') // Adjust to your `models` folder
const outputFile = join(modelsDir, 'index.ts')

const getModelFiles = (dir: string): string[] => {
  let results: string[] = []
  const list = fs.readdirSync(dir)

  list.forEach((file) => {
    const filePath = join(dir, file)
    const stat = fs.statSync(filePath)

    if (stat && stat.isDirectory()) {
      // Recursively get model files from subdirectories
      results = results.concat(getModelFiles(filePath))
    } else if (file.endsWith('.model.ts') && file !== 'index.ts') {
      results.push(filePath)
    }
  })

  return results
}

const files = getModelFiles(modelsDir)

const exports = files.map((file) => {
  const relativePath = path.relative(modelsDir, file).replace(/\\/g, '/') // Normalize path for exports
  return `export * from './${relativePath.replace('.ts', '')}';`.trim()
})

fs.writeFileSync(outputFile, exports.join('\n'), 'utf8')
Enter fullscreen mode Exit fullscreen mode
  1. Save and Test the Script: Run the script to ensure it generates the src/script/generate-models.ts file correctly.
src/
├── scripts/
│   └── generateIndex.js
├── models/
│   ├── user.model.ts
│   └── post.model.ts
└── index.ts
Enter fullscreen mode Exit fullscreen mode

Implementing Chokidar CLI

  1. Install Chokidar CLI: If you haven’t already, install Chokidar CLI globally using npm or save as a dev dependency in your project:

global install

npm install -g chokidar-cli
Enter fullscreen mode Exit fullscreen mode

dev dependency install

npm install --save-dev chokidar-cli
Enter fullscreen mode Exit fullscreen mode
  1. Set Up File Watching: Use Chokidar to watch your models directory and trigger the script whenever a change is detected:

We will create a few scrips in package.json file to watch the files and run the script.

"scripts": {
    "dev": "tsx watch src/index.ts",
    "start": "node dist/index.js",
    "compile": "tsc && npm run copy-pug",
    "prebuild": "npm run generate-models",
    "build": "npm install && npm run compile",
    "generate-models": "tsx src/scripts/generate-models.ts",
    "watch-files": "chokidar \"src/models/**/*.model.ts\" -c \"npm run generate-model-exports\""
  },
Enter fullscreen mode Exit fullscreen mode

Note here we using tsx to run the script as we are using TypeScript, but you can replace this with ts-node(Typescript alt) or node (JavaScript) to run the script.

  1. Run the Command: Execute the above command in your terminal to start watching for changes.
npm run watch-files
Enter fullscreen mode Exit fullscreen mode

What Chakridar does is it watches the files and run the script whenever a change is detected.

  1. Check the index.ts File: Ensure that your models/index.ts file is correctly updated with the exports from your model files.
export * from './user.model'
export * from './post.model'
Enter fullscreen mode Exit fullscreen mode

Running the Setup

With everything in place, any time you add or modify a model file, Chokidar will automatically run your script, ensuring that your models/index.ts file is always up to date. This setup will significantly streamline your workflow and enhance productivity.

Conclusion

By implementing this script and using Chokidar CLI, you can automate the management of your MongoDB model exports, allowing you to focus more on development and less on repetitive tasks. Give it a try and see how it boosts your backend code productivity!

But this Chokidar CLI can be used for any file watching and running scripts like compling your Sass, Less or Stylus files, running tests, etc. It's a powerful tool that can save you a lot of time and effort.

Drop some 💖 and 🔥 if you found this article helpful and have any questions or need further clarification, feel free to reach out. Happy coding!

Get In Touch

Top comments (14)

Collapse
 
sahilchaubey profile image
sahilchaubey03

This is a game changer! I've been manually updating my models forever. Can't wait to try out this Chokidar CLI setup. Thanks for sharing

Collapse
 
thesohailjafri profile image
Sohail Jafri

Do let me know if you find any difficulties

Collapse
 
sahil_chaubey_45db49be580 profile image
WebDevReigns

If someone wanted to customize this further, like adding custom export formats, how difficult would that be to integrate with Chokidar?

Collapse
 
thesohailjafri profile image
Sohail Jafri

No, it will be quite easy to alter the script and add any required format like js, ts or css

Collapse
 
devops_devrel profile image
Memories From

The section on implementing the script was really helpful. I'm new to managing multiple models, and this really demystified the process. Thanks for writing this!

Collapse
 
thesohailjafri profile image
Sohail Jafri

Ik right its having a superpower

Collapse
 
sahil_reigns_4776e181e6f7 profile image
ReignsEmpire

Are there any best practices you’d suggest for testing this setup to make sure it’s running as expected?

Collapse
 
thesohailjafri profile image
Sohail Jafri

I would just learning a test framework like jest to do test-driven development

Collapse
 
superdevchaurasia profile image
SAHIL RAJESH KUMAR CHAUBEY

Great Article!

Collapse
 
thesohailjafri profile image
Sohail Jafri

Hey thanks mate!!

Collapse
 
sahil_chaubey_5417dfa7caa profile image
ReactNinja

Thanks for the clear instructions

Collapse
 
thesohailjafri profile image
Sohail Jafri

Glad they were clear and you got the point

Collapse
 
sahil_reigns_4776e181e6f7 profile image
ReignsEmpire

Thanks for the clear instructions!!!!!

Collapse
 
thesohailjafri profile image
Sohail Jafri

Hey thanks for feedback