Monday, 3 April 2017

node.js creating custom module with function to return a value (kind of a dbo using mssql)

I've never had to do this before. I've created myModule.GetRecord() and I can see the recordset successfully has the expected record. However, ret in router.get() is undefined.

I believe because I need to catch the returned value in a callback.

I don't know how to define this module/function for a callback (if that is what I am appropriately looking to do) or how to call this function for a callback.

I've tried a few different things i.e. the typical GetRecord(ret, function () { ... }); But didn't see anything that appeared to work. And I read a bunch on the line but didn't find what I believe I'm looking for.

I really don't care to much about how I get there, but all I'm really trying to do is have mm.GetRecord()'s returned value in some usable form in the router.get()

--- myModulefile.js ---

'use strict';

module.exports = {

    GetRecord: function (id) {
        var sql = require('mssql');

        sql.connect({ user: 'sa', ... database: 'name' }, function (err) {
            if (err) { console.log(err); return null; }
            var cmd = new sql.Request();
            cmd.query('select * from Records where id = ' + id, function (err, rs) {
                if (err) { console.log(err); return null; }
                if (rs.recordset.length > 0) {
                    console.log('rs[0]', rs.recordset[0]);
                    return rs.recordset[0];
                } else {
                    return null;
                }
            });
        });
    }
};

--- myRouter.js ----

const express = require('express');
const router = express.Router();
const mm = require('../myModule');


router.get('/:id', function (req, res) {
    var id = req.params.id;
    var ret = mm.GetRecord(id)
    console.log('ret', ret);
    if (ret == null)
        ret = JSON.stringify({ ID: -1, f1: 'unknown' });
    res.send(ret);
});

module.exports = router;



via user2367083

No comments:

Post a Comment