Explorar el Código

replace orm frameworks to native drivers (#4329)

Marco Talento hace 6 años
padre
commit
c4da8f45d5

+ 5 - 5
frameworks/JavaScript/fastify/app.js

@@ -1,5 +1,5 @@
-const cluster = require('cluster');
-const numCPUs = require('os').cpus().length;
+const cluster = require("cluster");
+const numCPUs = require("os").cpus().length;
 
 if (cluster.isMaster) {
   // Fork workers.
@@ -7,12 +7,12 @@ if (cluster.isMaster) {
     cluster.fork();
   }
 
-  console.log('Master starting ' + new Date().toISOString());
+  console.log("Master starting " + new Date().toISOString());
 
-  cluster.on('exit', () => {
+  cluster.on("exit", () => {
     process.exit(1);
   });
 } else {
   // worker task
-  require('./create-server');
+  require("./create-server");
 }

+ 31 - 28
frameworks/JavaScript/fastify/create-server.js

@@ -1,48 +1,51 @@
-const fastify = require('fastify')();
-const handler = require('./handlers/handler');
+const fastify = require("fastify")();
+const handlers = require("./handlers");
 
-fastify.register(require('point-of-view'), {
+fastify.register(require("point-of-view"), {
   engine: {
-    ejs: require('handlebars')
+    ejs: require("handlebars")
   },
-  templates: __dirname + '/views'
-})
+  templates: __dirname + "/views"
+});
 
 fastify.use((req, reply, next) => {
-  reply.setHeader('Server', 'Fastify')
+  reply.setHeader("Server", "Fastify");
 
-  next()
-})
+  next();
+});
 
-fastify.get('/json', (req, reply) => {
-  reply.header('Content-Type', 'application/json')
+fastify.get("/json", (req, reply) => {
+  reply
+    .header("Content-Type", "application/json")
     .code(200)
-    .send({ message: 'Hello, World!' });
-})
+    .send({ message: "Hello, World!" });
+});
 
-fastify.get('/plaintext', (req, reply) => {
-  reply.header('Content-Type', 'text/plain')
+fastify.get("/plaintext", (req, reply) => {
+  reply
+    .header("Content-Type", "text/plain")
     .code(200)
-    .send('Hello, World!');
+    .send("Hello, World!");
 });
 
-const handlerName = process.env.NODE_HANDLER;
+const database = process.env.DATABASE;
 
-if (handlerName) {
-  const dbLayer = require(`./handlers/${handlerName}`);
+if (database) {
+  const dbLayer = require(`./db/${database}`);
+  const routerHandler = handlers(dbLayer);
 
-  const routerHandler = handler(dbLayer);
-
-  fastify.get('/db', routerHandler.SingleQuery);
-  fastify.get('/queries', routerHandler.MultipleQueries);
-  fastify.get('/fortunes', routerHandler.Fortunes);
-  fastify.get('/updates', routerHandler.Updates);
+  fastify.get("/db", routerHandler.singleQuery);
+  fastify.get("/queries", routerHandler.multipleQueries);
+  fastify.get("/fortunes", routerHandler.fortunes);
+  fastify.get("/updates", routerHandler.updates);
 }
 
-fastify.listen(8080, '0.0.0.0', err => {
+fastify.listen(8080, "0.0.0.0", err => {
   if (err) {
     throw err;
   }
 
-  console.log(`Worker started and listening on http://0.0.0.0:8080 ${new Date().toISOString()}`);
-})
+  console.log(
+    `Worker started and listening on http://0.0.0.0:8080 ${new Date().toISOString()}`
+  );
+});

+ 50 - 0
frameworks/JavaScript/fastify/db/mongo.js

@@ -0,0 +1,50 @@
+const MongoClient = require("mongodb").MongoClient;
+
+const mongoUrl = "mongodb://tfb-database:27017";
+const dbName = "hello_world";
+
+let client;
+
+async function getCollection(name) {
+  if (!client) {
+    client = await MongoClient.connect(
+      mongoUrl,
+      { useNewUrlParser: true }
+    );
+  }
+
+  const db = client.db(dbName);
+
+  return db.collection(name);
+}
+
+async function allFortunes() {
+  const collection = await getCollection("fortune");
+  const fortunes = await collection.find({}, { projection: { _id: 0 } });
+
+  return fortunes.toArray();
+}
+
+async function getWorld(id) {
+  const collection = await getCollection("world");
+
+  return collection.findOne({ id }, { projection: { _id: 0 } });
+}
+
+async function saveWorlds(worlds) {
+  const collection = await getCollection("world");
+
+  const bulk = collection.initializeUnorderedBulkOp();
+
+  worlds.forEach(world => {
+    bulk.find({ id: world.id }).updateOne(world);
+  });
+
+  return bulk.execute();
+}
+
+module.exports = {
+  getWorld,
+  saveWorlds,
+  allFortunes
+};

+ 41 - 0
frameworks/JavaScript/fastify/db/mysql.js

@@ -0,0 +1,41 @@
+const knex = require("knex")({
+  client: "mysql2",
+  connection: {
+    host: "tfb-database",
+    user: "benchmarkdbuser",
+    password: "benchmarkdbpass",
+    database: "hello_world"
+  }
+});
+
+async function allFortunes() {
+  return knex("Fortune").select("*");
+}
+
+async function getWorld(id) {
+  return knex("World")
+    .first()
+    .where({ id });
+}
+
+async function saveWorlds(worlds) {
+  const updates = [];
+
+  worlds.forEach(world => {
+    const { id, randomNumber } = world;
+
+    updates.push(
+      knex("World")
+        .update({ randomNumber })
+        .where({ id })
+    );
+  });
+
+  return Promise.all(updates);
+}
+
+module.exports = {
+  getWorld,
+  saveWorlds,
+  allFortunes
+};

+ 41 - 0
frameworks/JavaScript/fastify/db/postgres.js

@@ -0,0 +1,41 @@
+const knex = require("knex")({
+  client: "pg",
+  connection: {
+    host: "tfb-database",
+    user: "benchmarkdbuser",
+    password: "benchmarkdbpass",
+    database: "hello_world"
+  }
+});
+
+async function allFortunes() {
+  return knex("Fortune").select("*");
+}
+
+async function getWorld(id) {
+  return knex("World")
+    .first()
+    .where({ id });
+}
+
+async function saveWorlds(worlds) {
+  const updates = [];
+
+  worlds.forEach(world => {
+    const { id, randomNumber } = world;
+
+    updates.push(
+      knex("World")
+        .update({ randomnumber: randomNumber })
+        .where({ id })
+    );
+  });
+
+  return Promise.all(updates);
+}
+
+module.exports = {
+  getWorld,
+  saveWorlds,
+  allFortunes
+};

+ 2 - 2
frameworks/JavaScript/fastify/fastify-mysql.dockerfile

@@ -1,10 +1,10 @@
-FROM node:10.12.0
+FROM node:11.6.0
 
 COPY ./ ./
 
 RUN npm install
 
 ENV NODE_ENV production
-ENV NODE_HANDLER sequelize
+ENV DATABASE mysql
 
 CMD ["node", "app.js"]

+ 2 - 2
frameworks/JavaScript/fastify/fastify-postgres.dockerfile

@@ -1,10 +1,10 @@
-FROM node:10.12.0
+FROM node:11.6.0
 
 COPY ./ ./
 
 RUN npm install
 
 ENV NODE_ENV production
-ENV NODE_HANDLER sequelize-postgres
+ENV DATABASE postgres
 
 CMD ["node", "app.js"]

+ 2 - 2
frameworks/JavaScript/fastify/fastify.dockerfile

@@ -1,10 +1,10 @@
-FROM node:10.12.0
+FROM node:11.6.0
 
 COPY ./ ./
 
 RUN npm install
 
 ENV NODE_ENV production
-ENV NODE_HANDLER mongoose
+ENV DATABASE mongo
 
 CMD ["node", "app.js"]

+ 18 - 15
frameworks/JavaScript/fastify/handlers/handler.js → frameworks/JavaScript/fastify/handlers.js

@@ -1,36 +1,39 @@
-const h = require('../helper');
+const h = require("./helper");
 
 /**
  * @param databaseLayer
- * @returns {{SingleQuery: function(*), MultipleQueries: function(*), Fortunes: function(*), Updates: function(*)}}
+ * @returns {{singleQuery: function(*), multipleQueries: function(*), fortunes: function(*), updates: function(*)}}
  */
-module.exports = (databaseLayer) => ({
-  SingleQuery: async (req, reply) => {
-    const world = await databaseLayer.getWorldLean(h.randomTfbNumber());
+module.exports = databaseLayer => ({
+  singleQuery: async (req, reply) => {
+    const world = await databaseLayer.getWorld(h.randomTfbNumber());
 
     reply.send(world);
   },
 
-  MultipleQueries: async (req, reply) => {
+  multipleQueries: async (req, reply) => {
     const queries = h.getQueries(req.query.queries);
     const promisesArray = [];
 
     for (let i = 0; i < queries; i++) {
-      promisesArray.push(databaseLayer.getWorldLean(h.randomTfbNumber()));
+      promisesArray.push(databaseLayer.getWorld(h.randomTfbNumber()));
     }
 
-    reply.send(await Promise.all(promisesArray));
+    const worlds = await Promise.all(promisesArray);
+
+    reply.send(worlds);
   },
 
-  Fortunes: async (req, reply) => {
+  fortunes: async (req, reply) => {
     const fortunes = await databaseLayer.allFortunes();
+
     fortunes.push(h.additionalFortune);
     fortunes.sort((a, b) => a.message.localeCompare(b.message));
 
-    reply.view('fortunes.hbs', { fortunes })
+    reply.view("fortunes.hbs", { fortunes });
   },
 
-  Updates: async (req, reply) => {
+  updates: async (req, reply) => {
     const queries = h.getQueries(req.query.queries);
     const worldPromises = [];
 
@@ -42,11 +45,11 @@ module.exports = (databaseLayer) => ({
 
     const worldsToUpdate = worlds.map(world => {
       world.randomNumber = h.randomTfbNumber();
-      return world
+      return world;
     });
 
-    const updatedWorlds = await databaseLayer.saveWorlds(worldsToUpdate);
+    await databaseLayer.saveWorlds(worldsToUpdate);
 
-    reply.send(updatedWorlds);
+    reply.send(worldsToUpdate);
   }
-});
+});

+ 0 - 12
frameworks/JavaScript/fastify/handlers/mongoose.js

@@ -1,12 +0,0 @@
-const { Worlds, Fortunes } = require('../models/mongoose');
-
-module.exports = {
-  getWorld: _id => Worlds.findById(_id),
-  getWorldLean: _id => Worlds.findById(_id).select('-_id').lean(),
-  allFortunes: () => Fortunes.find({}).select('-_id'),
-  saveWorlds: async (worlds) => {
-    const updatedWorlds = await Promise.all(worlds.map(world => world.save()))
-
-    return updatedWorlds.map((w) => ({ id: w._id, randomNumber: w.randomNumber }))
-  }
-};

+ 0 - 8
frameworks/JavaScript/fastify/handlers/sequelize-postgres.js

@@ -1,8 +0,0 @@
-const {Worlds, Fortunes} = require('../models/sequelize-postgres');
-
-module.exports = {
-  getWorld: id => Worlds.findOne({where: {id}}),
-  getWorldLean: id => Worlds.findOne({where: {id}, raw: true}),
-  allFortunes: () => Fortunes.findAll(),
-  saveWorlds: worlds => Promise.all(worlds.map(world => world.save())),
-};

+ 0 - 8
frameworks/JavaScript/fastify/handlers/sequelize.js

@@ -1,8 +0,0 @@
-const {Worlds, Fortunes} = require('../models/sequelize');
-
-module.exports = {
-  getWorld: id => Worlds.findOne({where: {id}}),
-  getWorldLean: id => Worlds.findOne({where: {id}, raw: true}),
-  allFortunes: () => Fortunes.findAll(),
-  saveWorlds: worlds => Promise.all(worlds.map(world => world.save())),
-};

+ 2 - 2
frameworks/JavaScript/fastify/helper.js

@@ -1,12 +1,12 @@
 module.exports = {
   randomTfbNumber: () => Math.floor(Math.random() * 10000) + 1,
 
-  getQueries: (queries) => {
+  getQueries: queries => {
     return Math.min(Math.max(parseInt(queries) || 1, 1), 500);
   },
 
   additionalFortune: {
     id: 0,
-    message: 'Additional fortune added at request time.'
+    message: "Additional fortune added at request time."
   }
 };

+ 0 - 30
frameworks/JavaScript/fastify/models/mongoose.js

@@ -1,30 +0,0 @@
-const Mongoose = require('mongoose');
-
-Mongoose.Promise = Promise;
-
-const { SchemaTypes } = Mongoose;
-
-Mongoose.connect('mongodb://tfb-database:27017/hello_world', { useNewUrlParser: true })
-  .catch(error => {
-    console.error(error);
-    process.exit(1);
-  });
-
-const WorldSchema = new Mongoose.Schema({
-  _id: Number,
-  randomNumber: Number,
-}, {
-    collection: 'world',
-    versionKey: false
-  });
-
-const FortuneSchema = new Mongoose.Schema({
-  id: SchemaTypes.Number,
-  message: SchemaTypes.String,
-}, {
-    collection: 'fortune',
-    versionKey: false,
-  });
-
-module.exports.Worlds = Mongoose.model('World', WorldSchema, 'world');
-module.exports.Fortunes = Mongoose.model('Fortune', FortuneSchema, 'fortune');

+ 0 - 37
frameworks/JavaScript/fastify/models/sequelize-postgres.js

@@ -1,37 +0,0 @@
-const Sequelize = require('sequelize');
-const sequelize = new Sequelize('hello_world', 'benchmarkdbuser', 'benchmarkdbpass', {
-  host: 'tfb-database',
-  dialect: 'postgres',
-  logging: false
-});
-
-const { DataTypes } = Sequelize;
-const Worlds = sequelize.define('World', {
-  id: {
-    type: DataTypes.INTEGER,
-    primaryKey: true
-  },
-  randomNumber: {
-    type: DataTypes.INTEGER,
-    field: 'randomnumber'
-  },
-}, {
-    timestamps: false,
-    freezeTableName: true
-  });
-
-const Fortunes = sequelize.define('Fortune', {
-  id: {
-    type: DataTypes.INTEGER,
-    primaryKey: true
-  },
-  message: { type: DataTypes.STRING }
-}, {
-    timestamps: false,
-    freezeTableName: true
-  });
-
-module.exports = {
-  Worlds,
-  Fortunes,
-};

+ 0 - 34
frameworks/JavaScript/fastify/models/sequelize.js

@@ -1,34 +0,0 @@
-const Sequelize = require('sequelize');
-const sequelize = new Sequelize('hello_world', 'benchmarkdbuser', 'benchmarkdbpass', {
-  host: 'tfb-database',
-  dialect: 'mysql',
-  logging: false
-});
-
-const { DataTypes } = Sequelize;
-const Worlds = sequelize.define('World', {
-  id: {
-    type: DataTypes.INTEGER,
-    primaryKey: true
-  },
-  randomNumber: { type: DataTypes.INTEGER }
-}, {
-    timestamps: false,
-    freezeTableName: true
-  });
-
-const Fortunes = sequelize.define('Fortune', {
-  id: {
-    type: DataTypes.INTEGER,
-    primaryKey: true
-  },
-  message: { type: DataTypes.STRING }
-}, {
-    timestamps: false,
-    freezeTableName: true
-  });
-
-module.exports = {
-  Worlds,
-  Fortunes,
-};

+ 8 - 9
frameworks/JavaScript/fastify/package.json

@@ -1,17 +1,16 @@
 {
   "name": "fastify-tfb",
-  "version": "0.0.1",
+  "version": "0.0.2",
   "description": "Fastify tests for TechEmpower Framework Benchmarks.",
   "main": "app.js",
   "private": true,
   "dependencies": {
-    "fastify": "1.9.0",
-    "handlebars": "4.0.11",
-    "mongoose": "5.2.5",
-    "mysql2": "1.5.3",
-    "pg": "7.4.3",
-    "pg-hstore": "2.3.2",
-    "point-of-view": "1.1.0",
-    "sequelize": "4.37.10"
+    "fastify": "1.13.3",
+    "handlebars": "4.0.12",
+    "knex": "0.16.3",
+    "mongodb": "3.1.10",
+    "mysql2": "1.6.4",
+    "pg": "7.7.1",
+    "point-of-view": "2.1.0"
   }
 }