This article explains how you can automatically version your API using semantic versioning when you make changes and deploy your codes to your server.
I’m assuming that you are using Nodejs as your backend and have a git repository.
Versioning is used for keeping a record for all the changes made on API. It should be used to keep track of patches, minor and major changes which are done on the API.
We are going to follow the semantic versioning which is represented by major, minor and patch number separated by dots. For example v1.0.0 here the version is having 1 as a major, 0 as minor and patch.
Each time we release a bug fix/patch we increment the patch number in the version Ie v1.0.1 And when there is a new feature added to the API lets say a new field in the API or a new endpoint then we increase the minor version and resets the patch version to 0 Then the version becomes v1.1.0
And if you introduce a new breaking change to the API, that is if the apps which are consuming the API needs a code change to function properly then that’s a breaking change or a major change in which case you increment the major version and resets minor and patch version.
If you are in development phase then you might want to keep your major version as 0
And when you are in beta then keep the version as v1.0.0-beta.0 and for any new updates increment the beta number, ie v1.0.0-beta.1, v1.0.0-beta.2 and so on.
npm install git-describe path fs-extra package.json
const { gitDescribeSync } = require('git-describe');
const { version } = require('package.json');
const { resolve, relative } = require('path');
const { writeFileSync } = require('fs-extra');
const gitInfo = gitDescribeSync({
dirtyMark: false,
dirtySemver: false
});
gitInfo.version = version;
const file = resolve(__dirname, 'constants', 'version.js');
writeFileSync(file,
`// IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
/* tslint:disable */
const VERSION = ${JSON.stringify(gitInfo, null, 4)};
module.exports = {
VERSION
};
/* tslint:enable */
`, { encoding: 'utf-8' });
console.log(`Wrote version info ${gitInfo.raw} to ${relative(resolve(__dirname, '..'), file)}`);
And make sure that you are not committing the auto-generated file.
Now when you make commits make sure that you do add tags to the git repo.
This can be done by adding
git tag -a v1.0.0
And when you run npm build, the post-install script will pick up this version number and write it to the constat dir which can be used by the app to display the current version in the API