Browse Source

1. Made the query for bulk update a bit readable. (#8555)

2. Updated the cluster code to use availableParallelism as used nowdays witth the recent node.js versions.
3. Updated to the ESM require modules which are used in all latest node.js projects instead of old CJS modules.
srisaiswaroop 1 year ago
parent
commit
0ec8ed488e

+ 6 - 5
frameworks/JavaScript/nodejs/app.js

@@ -1,5 +1,6 @@
-const cluster = require('cluster');
-const numCPUs = require('os').cpus().length;
+const cluster = require('node:cluster');
+const { availableParallelism } = require('node:os');
+const numCPUs = availableParallelism();
 
 process.env.NODE_HANDLER = 'postgres';
 
@@ -13,18 +14,18 @@ if (process.env.TFB_TEST_NAME === 'nodejs-mongodb') {
   process.env.NODE_HANDLER = 'mysql-raw';
 } else if (process.env.TFB_TEST_NAME === 'nodejs-postgres') {
   process.env.NODE_HANDLER = 'sequelize-postgres';
-}else if (process.env.TFB_TEST_NAME === 'nodejs-postgresjs-raw') {
+} else if (process.env.TFB_TEST_NAME === 'nodejs-postgresjs-raw') {
   process.env.NODE_HANDLER = 'postgres';
 }
 
-if (cluster.isPrimary) {
+if (numCPUs > 1 && cluster.isPrimary) {
   console.log(`Primary ${process.pid} is running`);
 
   // Fork workers.
   for (let i = 0; i < numCPUs; i++) {
     cluster.fork();
   }
-
+  
   cluster.on('exit', (worker, code, signal) => {
     console.log(`worker ${worker.process.pid} died`);
     process.exit(1);

+ 1 - 1
frameworks/JavaScript/nodejs/create-server.js

@@ -1,7 +1,7 @@
 // Forked workers will run this code when found to not be
 // the master of the cluster.
 
-const http = require('http');
+const http = require('node:http');
 const parseurl = require('parseurl'); // faster than native nodejs url package
 
 // Initialize routes & their handlers (once)

+ 6 - 6
frameworks/JavaScript/nodejs/handlers/postgres.js

@@ -17,14 +17,14 @@ const dbfind = async (id) =>
     (arr) => arr[0]
   );
 
-const dbbulkUpdate = async (worlds) =>
+const dbbulkUpdate = async (worlds) => {
+  const sorted = sql(worlds
+    .map((world) => [world.id, world.randomNumber])
+    .sort((a, b) => (a[0] < b[0] ? -1 : 1)));
   await sql`UPDATE world SET randomNumber = (update_data.randomNumber)::int
-  FROM (VALUES ${sql(
-    worlds
-      .map((world) => [world.id, world.randomNumber])
-      .sort((a, b) => (a[0] < b[0] ? -1 : 1))
-  )}) AS update_data (id, randomNumber)
+  FROM (VALUES ${sorted}) AS update_data (id, randomNumber)
   WHERE world.id = (update_data.id)::int`;
+};
 
 const dbgetAllWorlds = async () => sql`SELECT id, randomNumber FROM world`;