By Oleksii Rudenko November 9, 2015 9:00 PM
Generating Coupon/Voucher Codes in NodeJS

From time to time, it’s required to generate codes for users that they can use to claim some discounts or bonuses later. Instead of inventing something yourself, you can use the existing library called coupon-code:

npm install coupon-code --save

The interface of the module is simple. To generate a code, call generate:

var couponCode = require('coupon-code');

couponCode.generate(); // default settings 3 parts, each 4 character long

couponCode.generate({ parts: 3}); // generate 3 sections of the code
                                  // each of the default length
couponCode.generate({ partLen: 4 }); // generate default number of sections
                                       // of given length
couponCode.generate({ partLen: 5, parts: 2}); // generate 10-character code
                                                 // consisting of two sections

To validate a code, use validate method. This method does not only validate the entered code, it deals with the input errors as well. Before validating, the method uppercases the code and then replaces letters that are similar to numbers with numbers: O -> 0, Z -> 2, S -> 5 and I -> 1. So if user confuses some letters/numbers, his voucher will still be validated successfully.

For example,


couponCode.validate('G914-PLPB', { parts: 2}); // => G914-PLPB
// I is typed instead of 1
couponCode.validate('G9I4-PLPB', { parts: 2}); // returns the same as above

The validate method returns an empty string if the input is invalid and the canonical code if the input is valid even if there are input errors. Generation algorithm ensures that all versions with typos result in the same canonical code.

It’s important to provide the correct of the code (i.e. parts and partLen) as the library will not derive them.

Practical Usage

Uniqueness is not ensured by the algorithm. Therefore your application has to make sure that the generated code is unique. For example, if the check is possible in a synchronous manner:

var code = null;
do {
  code = couponCode.generate();
} while (!unique(code));

// code is unique here
return code;

Or with promises (similar with callbacks):


var couponCode = require('coupon-code');
var Promise = require('bluebird');

var count = 0;
// this is code that checks uniqueness and returns a promise
function check(code) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      count++;
      // first resolve with false, on second try resolve with true
      if (count === 1) {
        console.log(code + ' is not unique');
        resolve(false);
      } else {
        console.log(code + ' is unique');
        resolve(true);
      }
    }, 1000);
  });
}

var generateUniqueCode = Promise.method(function() {
  var code = couponCode.generate();
  return check(code)
    .then(function(result) {
      if (result) {
        return code;
      } else {
        return generateUniqueCode();
      }
    });
});

generateUniqueCode().then(function(code) {
  console.log(code);
});

Thanks for reading.