Home > OS >  How to create an unused database ID with node.js
How to create an unused database ID with node.js

Time:10-13

I want to create an ID for my program. The ID is random, but I must make sure that it not already exists in database. To do so, I search the ID, and if the search result is empty, then the ID passes, but if the search finds something, the process needs to start over.

In PHP I can do this logic for my code:

require('somesqlconnection.php');

$repeat = false;
do {
  $id = createId(50); // this is my function for creating random with 50 as length for the string
  $result = mysqli_query("SELECT * FROM users WHERE id = '$id'", $conn);
  $repeat = mysqli_num_rows($result) > 0;
} while ($repeat);

echo $id;

How can I implement the same logic in node.js that is basically executing in asynchronous?

I tried this but didn't work:

const util = require('util');
const sql = require('../sqlconnection.js');

let repeat = false;
const query = util.promisify(sql.query).bind(sql);
do {
  let id = createId(50);
  (async () => {
    const rows = await query(`SELECT id FROM users WHERE id = '${id}'`);
    repeat = rows.length > 0;
  })();
} while(repeat);

console.log(id);

CodePudding user response:

You could create a function that returns a promise for a new ID like this:

const util = require('util');
const sql = require('../sqlconnection.js');

sql.queryAsync = util.promisify(sql.query);

async function createNewId() {
  const newId = createId(50);
  const result = await sql.queryAsync('SELECT id FROM users WHERE id = ?', [newId]);
  return !result.length ? newId : createNewId();
}

This returns the new ID, or it calls itself again.

Usage is either with .then():

createNewId().then(newId => {
  console.log('found unused ID', newId);
  // do something with it
}).catch(err => {
  console.log('oops', err);
});

or inside an async function with await:

async function main() {
  try {
    const newId = await createNewId(); 
    console.log('found unused ID', newId);
    // do something with it
  } catch (err) {
    console.log('oops', err);
  }
}
  • Related