0

I have a node js and I want to generate code for activity_code, I want to generate code like these : LA0000000001 , LA0000000002 , LA0000000003 and so on sequentially. I have tried like this, but in the some case, when I submit 2 activities simultaneously, one of the activities will lose and not submit, sometimes also the code that enters double and causes the next activity cannot be submitted. What is wrong with my code? Thankyou for helping :)

this.insertMasterActivity = function(req, res) {
    var id = uuidv1();
    var activity_kode = null;
    var activity_subject = req.body.activity_subject;
    var created = new Date();

    connection.acquire(function(err, con) {
        con.query('select activity_kode from activities order by created desc limit 1', function(err, result) {
            con.release();
            if (err) {
                res.send({ status: 400, message: 'Activities Failed' });
            } else {
                // for generate activity_kode
                if (result.length != 0) {
                    var test = result[0].activity_kode;
                } else {
                    var test = "LA00000000000"
                }

                var pieces = test.split('LA');
                var lastNum = pieces[1];
                lastNum = parseInt(lastNum, 10);
                lastNum++;
                activity_kode = "LA" + ("00000000000" + lastNum).substr(-10);
                console.log(activity_kode);
                connection.acquire(function(err, con) {
                    con.query('INSERT INTO activities (id, activity_kode,activity_subject,created) VALUES (?,?,?,?)', [id, activity_kode, activity_subject, created], function(err, result) {
                        con.release();
                        // console.log(err);
                        if (err) {
                            res.send({ status: 400, message: 'creation failed' });
                        } else {
                            res.send({ status: 200, message: 'created successfully' });
                        }
                    });
                });
            };
        });
    });
}
Ratri
  • 337
  • 1
  • 7
  • 21

1 Answers1

0

I think this is what i call race-condition. I just know two way to solve this.

  1. Change the activity_kode to more unique activity_kode. like UUID.
  2. Use semaphore.

Change the activity_kode to UUID is easier than implementing semaphore. The concept of semaphore is like door with lock. If door is locked, don't access it, somebody inside. Put some boolean variable that work as door, check if that door locked first before generate activity_kode.

Many ways implementing it, since this is node.js question, callback or async-await may used in a way implementing semaphore. Somebody use flag field in a database, somebody use only with variable, somebody use empty file for it, somebody use plain text file only contain 1 or 0. Many ways.

I hope it help.

septianw
  • 121
  • 1
  • 6