Integrating Git Commits to MongoDB using NodeJS and Mongoose - Kevin Uriel Fonseca


An example of what  can be done with the git commands using the info in this post

The Why?

The reason of this function was mainly because I wanted to create a Changelog system that will help me to keep track of all the improvements or fucked ups that I do in my projects. Because of this, the need of me having to manually create an entry every single time there was a change in my code was really getting tiresome, thus I did my research to automatically create them.

According to Google, changelogs are also important.

Changelogs keep your customers informed and excited about all the new things you’re shipping to improve their lives. It increases customer engagement, trust, and credibility.

Requirement Summary

In this project, we will be integrating Git commits with MongoDB using NodeJS and Mongoose. The goal is to detect whenever a git commit -m "..." command has been run in the CLI and then add the committed text to a field in a MongoDB model. We will also ensure that duplicates are avoided.

The Code

To achieve this, we will first create a new Mongoose model with a text field to store the committed text. We will then create a file with the name of automaticChangelogs.js and use the child_process module in NodeJS to execute the git commit command and capture the committed text. Finally, we will use Mongoose to check if the text already exists in the database and only add it if it is unique.

const mongoose = require('mongoose');const { exec } = require('child_process');// Define the Mongoose schemaconst commitSchema = new mongoose.Schema({    title: {      type: String,      required: [true, 'Please add a title'],      trim: true    },    slug: {      type: String,      required: false    },    text: {      type: String,      trim: true,      required: [true, 'Please add a text'],      unique: true    },    status: {      type: String,      required: [true, 'Please add a status option'],      enum: ['draft', 'published', 'trash'],      default: 'published'    },    postType: {      type: [String],      enum: [        'bug',        'dependencies',        'duplicate',        'enhancement',        'help',        'invalid',        'question',        'wontfix'      ],      default: 'enhancement'    },    version: {      type: String,      required: false    }});// Create the Mongoose modelconst Commit = mongoose.model('Commit', commitSchema);

automaticChangelogs.js:

const { exec } = require('child_process')const Commit = require('../models/Commit')const automaticChangelogs = async (req, res, next) => {  exec('git log -1 --pretty=%B', async (error, stdout, stderr) => {    if (error) {      console.error(`exec error: ${error}`)    }    const existingCommit = await Commit.findOne({      text: stdout.trim(),    })    // Create document    if (!existingCommit) {      const changelog = await Commit.create({        title: 'Coming from the CLI',        slug: 'coming-from-the-cli',        text: stdout.trim(),        status: 'published',        version: '1.0.0'      })      changelog.save({ validateBeforeSave: true })    } else {      console.log('Commit with this text already exists');    }  })})module.exports = automaticChangelogs

In this code, we first define a Mongoose schema with a text field that is marked as unique and required. We then create a Mongoose model called Commit using this schema.

Next, we use the child_process module to execute the git log -1 --pretty=%B command, which returns the text of the most recent commit. We then remove any trailing whitespace from the text.

We then use Mongoose to check if the text already exists in the database by calling Commit.findOne({ text: stdout.trim() }); If the text is not found, we create a new Commit document and save it to the database using Commit.create({...}). If the text is found, we log a message indicating that a commit with this text already exists.

Furthermore, you can call the automaticChangelogs() method within your server.js file!.

Bye bye ūüôā

SIDEBAR
FOOTER