Kaynağa Gözat

Postgresexpress (#4068)

* [ci skip] updated readme to include the dbs added to the configurations

* [ci skip] fixed typo

* added two configurations to express - express-postgres and express-graphql-postgres, added a helper file to declutter some of the other implementations, as well. Finally, updated the readme

* minor additions to the readme
jenriquez-techempower 6 yıl önce
ebeveyn
işleme
287916bcd1

+ 6 - 0
frameworks/JavaScript/express/README.md

@@ -31,6 +31,9 @@ http://localhost:8080/mongoose
 MySQL:
 http://localhost:8080/sequelize
 
+PostgreSQL:
+http://localhost:8080/db
+
 ### Variable Query Test
 
 MongoDB:
@@ -38,3 +41,6 @@ http://localhost:8080/mongoose?queries=2
 
 MySQL:
 http://localhost:8080/sequelize?queries=2
+
+PostgreSQL:
+http://localhost:8080/queries?queries=2

+ 40 - 2
frameworks/JavaScript/express/benchmark_config.json

@@ -67,6 +67,25 @@
       "notes": "",
       "versus": "nodejs"
     },
+    "postgres": {
+      "db_url": "/db",
+      "query_url": "/queries?queries=",
+      "update_url": "/updates?queries=",
+      "fortune_url": "/fortunes",
+      "port": 8080,
+      "approach": "Realistic",
+      "classification": "Micro",
+      "database": "Postgres",
+      "framework": "express",
+      "language": "JavaScript",
+      "flavor": "NodeJS",
+      "orm": "Full",
+      "os": "Linux",
+      "database_os": "Linux",
+      "display_name": "express",
+      "notes": "",
+      "versus": "nodejs"
+    },
     "graphql-mysql": {
       "json_url": "/json",
       "plaintext_url": "/plaintext",
@@ -90,9 +109,28 @@
       "notes": "",
       "versus": "None"
     },
+    "graphql-postgres": {
+      "db_url": "/db",
+      "query_url": "/queries?queries=",
+      "update_url": "/updates?queries=",
+      "fortune_url": "/fortunes",
+      "port": 8080,
+      "approach": "Realistic",
+      "classification": "Micro",
+      "framework": "graphql-express-mysql",
+      "language": "JavaScript",
+      "flavor": "NodeJS",
+      "orm": "Full",
+      "platform": "NodeJS",
+      "webserver": "None",
+      "os": "Linux",
+      "database": "Postgres",
+      "database_os": "Linux",
+      "display_name": "express",
+      "notes": "",
+      "versus": "None"
+    },
     "graphql-mongodb": {
-      "json_url": "/json",
-      "plaintext_url": "/plaintext",
       "db_url": "/db",
       "query_url": "/queries?queries=",
       "fortune_url": "/fortunes",

+ 9 - 0
frameworks/JavaScript/express/express-graphql-postgres.dockerfile

@@ -0,0 +1,9 @@
+FROM node:10.3.0
+
+COPY ./ ./
+
+RUN npm install
+
+ENV NODE_ENV production
+
+CMD ["node", "graphql-postgres-app.js"]

+ 9 - 0
frameworks/JavaScript/express/express-postgres.dockerfile

@@ -0,0 +1,9 @@
+FROM node:10.3.0
+
+COPY ./ ./
+
+RUN npm install
+
+ENV NODE_ENV production
+
+CMD ["node", "postgresql-app.js"]

+ 17 - 0
frameworks/JavaScript/express/graphql-postgres-app.js

@@ -0,0 +1,17 @@
+const express = require('express');
+const app = express();
+const bodyParser = require('body-parser');
+const port = 8080;
+
+app.use(bodyParser.urlencoded({ extended:false }));
+app.use(bodyParser.json());
+
+// Routes
+
+const resolvers = require('./resolver-postgres');
+
+require('./routes')(app, resolvers);
+
+app.listen(port, () => {
+    console.log(`Listening on localhost:${port}`);
+});

+ 22 - 0
frameworks/JavaScript/express/helper.js

@@ -0,0 +1,22 @@
+module.exports = {
+
+    sanititizeTotal : (total) => {
+
+        var totalIterations;
+        if (!total || typeof(total) != 'number') {
+            totalIterations = 1;
+        } else if(total < 501 && total > 0) {
+            totalIterations = total;
+        } else if (total > 500) {
+            totalIterations = 500;
+        } else {
+            totalIterations = 1;
+        }
+        return totalIterations;
+    },
+
+    randomizeNum : () => {
+
+        return Math.floor(Math.random() * 10000) + 1
+    }
+}

+ 12 - 10
frameworks/JavaScript/express/package.json

@@ -3,17 +3,19 @@
   "version": "0.0.1",
   "private": true,
   "dependencies": {
-    "express": "4.16.2",
     "body-parser": "1.18.2",
-    "pug": "2.0.1",
-    "sequelize": "3.30.0",
-    "express-graphql": "^0.6.12",
-    "graphql": "^0.13.2",
-    "graphql-tools": "^3.1.1",
-    "mysql": "^2.16.0",
-    "mysql2": "^1.6.1",
+    "dateformat": "3.0.3",
+    "escape-html": "1.0.3",
+    "express": "4.16.2",
+    "express-graphql": "0.6.12",
+    "graphql": "0.13.2",
+    "graphql-tools": "3.1.1",
     "mongoose": "5.0.6",
-    "dateformat": "^3.0.3",
-    "escape-html": "^1.0.3"
+    "mysql": "2.16.0",
+    "mysql2": "1.6.1",
+    "pg": "4.2.0",
+    "pg-promise": "8.4.6",
+    "pug": "2.0.1",
+    "sequelize": "3.30.0"
   }
 }

+ 89 - 0
frameworks/JavaScript/express/postgresql-app.js

@@ -0,0 +1,89 @@
+const express = require('express'),
+  app = express(),
+  bodyParser = require('body-parser'),
+  pgp = require('pg-promise')(),
+  helper = require('./helper');
+
+const connection = {
+    db: 'hello_world',
+    username: 'benchmarkdbuser',
+    password: 'benchmarkdbpass',
+    host: 'tfb-database',
+    dialect: 'postgres'
+}
+
+const db = pgp(`postgres://${connection.username}:${connection.password}@${connection.host}:5432/${connection.db}`);
+
+app.set('view engine', 'pug');
+app.set('views', __dirname + '/views');
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(bodyParser.json());
+
+// Set headers for all routes
+app.use((req, res, next) => {
+    res.setHeader("Server", "Express");
+    return next();
+});
+
+// Routes
+app.get('/db', async (req, res) => {
+
+    let world = await getRandomWorld();
+
+    res.setHeader("Content-Type", "application/json");
+    res.json(world);
+});
+
+app.get('/queries', async (req, res) => {
+
+    const results = [],
+        queries = Math.min(parseInt(req.query.queries) || 1, 500);
+
+    for (let i = 0; i < queries; i++) {
+        
+        results.push(await getRandomWorld());
+    }
+
+    res.json(results)
+});
+
+app.get('/fortunes', async (req, res) => {
+
+    let fortunes = await getAllFortunes()
+    const newFortune = { id: 0, message: "Additional fortune added at request time." };
+    fortunes.push(newFortune);
+    fortunes.sort((a, b) => (a.message < b.message) ? -1 : 1);
+
+    res.render('fortunes/index', { fortunes: fortunes });
+});
+
+app.get('/updates', async (req, res) => {
+    const results = [],
+        queries = Math.min(parseInt(req.query.queries) || 1, 500);
+
+    for (let i = 1; i <= queries; i++) {
+
+        results.push(await updateRandomWorld())
+    }
+
+    res.json(results);
+});
+
+const getRandomWorld = async () => {
+
+    return await db.one(`select * from world where id = ${helper.randomizeNum()}`, [true])
+};
+
+const updateRandomWorld = async () => {
+
+    return await db.oneOrNone(`update world set randomNumber = ${helper.randomizeNum()} where id = ${helper.randomizeNum()} returning id, randomNumber`, [true])
+};
+
+const getAllFortunes = async () => {
+
+    return await db.many('select * from fortune', [true]);
+};
+
+app.listen(8080, () => {
+    console.log('listening on port 8080');
+});

+ 6 - 26
frameworks/JavaScript/express/resolver-mongo.js

@@ -1,4 +1,5 @@
 const mongoose = require('mongoose');
+const helper = require('./helper');
 
 const Schema = mongoose.Schema,
   ObjectId = Schema.ObjectId;
@@ -21,19 +22,14 @@ const FortuneSchema = new mongoose.Schema({
 
 // Methods
 
-const randomizeNum = () => {
-
-    return Math.floor(Math.random() * 10000) + 1;
-};
-
 async function arrayOfRandomWorlds(totalWorldToReturn) {
 
-    var totalIterations = sanititizeTotal(totalWorldToReturn);
+    var totalIterations = helper.sanititizeTotal(totalWorldToReturn);
     var arr = [];
 
     return new Promise(async (resolve, reject) => {
         for(var i = 0; i < totalIterations; i++) {
-            arr.push(await World.findOne({ id: randomizeNum() }));
+            arr.push(await World.findOne({ id: helper.randomizeNum() }));
         }
         if(arr.length == totalIterations) {
             resolve(arr);
@@ -43,13 +39,13 @@ async function arrayOfRandomWorlds(totalWorldToReturn) {
 
 async function updateRandomWorlds(totalToUpdate) {
 
-    const totalIterations = sanititizeTotal(totalToUpdate);
+    const totalIterations = helper.sanititizeTotal(totalToUpdate);
     var arr = [];
 
     return new Promise(async (resolve, reject) => {
         for(var i = 0; i < totalIterations; i++) {
 
-            arr.push(await World.findOneAndUpdate({ id: randomizeNum() }, { randomNumber: randomizeNum() }));
+            arr.push(await World.findOneAndUpdate({ id: helper.randomizeNum() }, { randomNumber: helper.randomizeNum() }));
         }
         if(arr.length == totalIterations) {
             resolve(arr);
@@ -57,22 +53,6 @@ async function updateRandomWorlds(totalToUpdate) {
     });
 };
 
-const sanititizeTotal = (total) => {
-
-    var totalIterations;
-
-    if (!total) {
-        totalIterations = 1;
-    } else if(total < 501 && total > 0) {
-        totalIterations = total;
-    } else if (total > 500) {
-        totalIterations = 500;
-    } else {
-        totalIterations = 1;
-    }
-    return totalIterations;
-};
-
 const sayHello = () => {
 
     var helloWorld = new Object;
@@ -85,7 +65,7 @@ module.exports = {
     Query: {
         helloWorld: () => sayHello(),
         getAllWorlds: async() => await World.find({}),
-        singleDatabaseQuery: async() => await World.findOne({ id: randomizeNum() }),
+        singleDatabaseQuery: async() => await World.findOne({ id: helper.randomizeNum() }),
         multipleDatabaseQueries: async(parent, args) => await arrayOfRandomWorlds(args.total),
         getWorldById: async(parent, args) => await World.findById(args.id),
         getAllFortunes: async() => await Fortune.find({}),

+ 80 - 0
frameworks/JavaScript/express/resolver-postgres.js

@@ -0,0 +1,80 @@
+const pgp = require('pg-promise')();
+const helper = require('./helper');
+
+// MySQL
+
+const connection = {
+    db: 'hello_world',
+    username: 'benchmarkdbuser',
+    password: 'benchmarkdbpass',
+    host: 'tfb-database',
+    dialect: 'postgres'
+}
+
+const db = pgp(`postgres://${connection.username}:${connection.password}@${connection.host}:5432/${connection.db}`);
+
+async function arrayOfRandomWorlds(totalWorldsToReturn) {
+
+    var totalIterations = helper.sanititizeTotal(totalWorldsToReturn);
+    var arr = [];
+
+    return new Promise(async(resolve, reject) => {
+
+        for(var i = 0; i < totalIterations; i++) {
+            arr.push(await getRandomWorld());
+        }
+        
+        if(arr.length == totalIterations) {
+            resolve(arr);
+        }
+    });
+};
+
+async function updateRandomWorlds(totalToUpdate) {
+
+    const total = helper.sanititizeTotal(totalToUpdate);
+    var arr = [];
+
+    return new Promise(async(resolve, reject) => {
+        for(var i = 0; i < total; i++) {
+            arr.push(await updateRandomWorld());
+        }
+
+        if(arr.length === total) resolve(arr)
+    });
+};
+
+const getRandomWorld = async () => {
+
+    let world = await db.one(`select * from World where id = ${helper.randomizeNum()}`, [true])
+    return {"id": world.id, "randomNumber": world.randomnumber};
+};
+
+const updateRandomWorld = async () => {
+
+    let world = await db.oneOrNone(`update world set randomNumber = ${helper.randomizeNum()} where id = ${helper.randomizeNum()} returning id, randomNumber`, [true])
+    return {"id": world.id, "randomNumber": world.randomnumber};
+};
+
+const getAllFortunes = async () => {
+
+    return await db.many('select * from fortune', [true]);
+};
+
+module.exports = {
+    Query: {
+        singleDatabaseQuery: async() => await getRandomWorld(),
+        multipleDatabaseQueries: async(parent, args) => await arrayOfRandomWorlds(args.total),
+        getAllFortunes: async() => await getAllFortunes(),
+        getRandomAndUpdate: async(parent, args) => await updateRandomWorlds(args.total)
+    },
+    Mutation: {
+        createWorld: async(parent, args) => {
+            let randInt = Math.floor(Math.random() * 1000) + 1;
+            return await World.create({ id: null, randomNumber: randInt });
+        },
+        updateWorld: async(parent, args) => {
+            return await World.update({id: args.id, randomNumber: args.randomNumber});
+        }
+    }
+}

+ 7 - 28
frameworks/JavaScript/express/resolver.js

@@ -1,4 +1,5 @@
 const Sequelize = require('sequelize');
+const helper = require('./helper');
 
 // MySQL
 
@@ -47,20 +48,14 @@ const Fortune = sequelize.define('fortune', {
       freezeTableName: true
 });
 
-const randomizeNum = () => {
-
-    let randomInt = Math.floor(Math.random() * 10000) + 1
-    return randomInt;
-}
-
 async function arrayOfRandomWorlds(totalWorldToReturn) {
 
-    var totalIterations = sanititizeTotal(totalWorldToReturn);
+    var totalIterations = helper.sanititizeTotal(totalWorldToReturn);
     var arr = [];
 
     return new Promise(async (resolve, reject) => {
         for(var i = 0; i < totalIterations; i++) {
-            let world = await World.findById(randomizeNum());
+            let world = await World.findById(helper.randomizeNum());
             arr.push(world);
         }
         if(arr.length == totalIterations) {
@@ -71,15 +66,15 @@ async function arrayOfRandomWorlds(totalWorldToReturn) {
 
 async function updateRandomWorlds(totalToUpdate) {
 
-    const total = sanititizeTotal(totalToUpdate);
+    const total = helper.sanititizeTotal(totalToUpdate);
     var arr = [];
 
     return new Promise(async (resolve, reject) => {
         for(var i = 0; i < total; i++) {
 
-            const world = await World.findById(randomizeNum());
+            const world = await World.findById(helper.randomizeNum());
             world.updateAttributes({
-                randomNumber: randomizeNum()
+                randomNumber: helper.randomizeNum()
             })
             arr.push(world);
         }
@@ -89,22 +84,6 @@ async function updateRandomWorlds(totalToUpdate) {
     });
 };
 
-const sanititizeTotal = (total) => {
-
-    var totalIterations;
-
-    if (!total || typeof(total) != 'number') {
-        totalIterations = 1;
-    } else if(total < 501 && total > 0) {
-        totalIterations = total;
-    } else if (total > 500) {
-        totalIterations = 500;
-    } else {
-        totalIterations = 1;
-    }
-    return totalIterations;
-};
-
 const sayHello = () => {
 
     var helloWorld = new Object;
@@ -117,7 +96,7 @@ module.exports = {
     Query: {
         helloWorld: () => sayHello(),
         getAllWorlds: async() => await World.findAll(),
-        singleDatabaseQuery: async() => await World.findById(randomizeNum()),
+        singleDatabaseQuery: async() => await World.findById(helper.randomizeNum()),
         multipleDatabaseQueries: async(parent, args) => await arrayOfRandomWorlds(args.total),
         getWorldById: async(parent, args) => await World.findById(args.id),
         getAllFortunes: async() => await Fortune.findAll(),