I am currently learning how to create nodejs express rest api using async making it fully scaleable and secure.
My goal is to ensure maximum functionality and speed, currently I am using MVC structure with route, controller, service and model.
Database is mysql and using mysql2 pool.
I am looking to know if the example snippets of code below are optimised as best as possible and correctly using async or is there a more efficient way ?
Route
'use strict';
const express = require('express');
const app = express.Router();
const Stats_controller = require('../controllers/stats');
app.get('/stats', Stats_controller.getStats);
module.exports = app;
Controller (unsure here about the async how its been used)
'use strict';
const statsService = require('../services/stats.js');
const getStats = async (req, res, next) => {
statsService.getStats(function(err, result) {
if (err)
res.send(err);
res.json(result);
});
};
module.exports.getStats = getStats;
Service
'use strict';
var coinsModel = require('../models/stats.js');
const getStats = async function(result) {
const res = await coinsModel.getStats();
var responseData = {
"status":"success",
"data":res
}
result(null, responseData);
}
module.exports.getStats = getStats;
Model
'use strict';
var db = require('../config/conf.js');
const getStats = async function() {
return new Promise((resolve) => {
db.connection.query("SELECT * FROM stats", function (err, res) {
if(!err){
resolve(res)
}else{
resolve([])
}
});
});
}
module.exports.getStats = getStats;