Giter VIP home page Giter VIP logo

express4-tedious's Introduction

Express4 Tedious Middleware

Express4 middleware that enables you to create REST API using SQL Server and Tedious.

Contents

Setup
Initializing data access components
Create REST API

Setup

To install Tedious Express4 package, run the following command:

npm install express4-tedious --save 

Initialize Middleware

In order to initialize data access middleware, you need to add sql method to your request when you initialize express app and routes:

var express = require('express');
var tediousExpress = require('express4-tedious');

var app = express();
app.use(function (req, res, next) {
    req.sql = tediousExpress(req, {connection object});
    next();
});

This call should be used before any other route definition. Connection object should look like:

{
	"server"  : "<<server name or ip>>",
	"userName": "<<user name>>",
	"password": "<<password>>",
	"options": { "encrypt": true, "database": "<<database name>>" }
}

Use "encrypt": true if database is hosted in Azure SQL.

Create REST API

Once you setup the middleware, you can easily create REST API using T-SQL queries:

/* GET product listing. */
router.get('/', function (req, res) {

    req.sql("select * from Product for json path")
        .into(res);

});

In the sql method you can specify T-SQL query that should be executed. Method into will stream results of the query into response object. [] will be sent to the client if results are not returned by query. You can provide second patamater that represents a custom string that should be returned if there is no response from database.

You can also create REST API that uses parameters:

/* GET product by id. */
router.get('/:id', function (req, res) {
    
    req.sql("select * from Product where id = @id for json path, without_array_wrapper")
        .param('id', req.params.id, TYPES.Int)
        .into(res, '{}');

});

You can create REST APIs that are invoked using POST, PUT, and DELETE methods, and execute SQL query using exec method (without results returned to the client):

/* PUT update product. */
router.put('/:id', function (req, res) {
    
    req.sql("exec updateProduct @id, @product")
        .param('id', req.params.id, TYPES.Int)
        .param('product', req.body, TYPES.NVarChar)
        .exec(res);

});

Note: you need to provide res object to the exec method, because this method will return status code to the client.

Handling errors

This middleware returns error 500 if any error happens with descirption of the error as plain text.

You can customize the function that handles the error and provide your own error handler:

/* PUT update product. */
router.put('/:id', function (req, res) {
    
    req.sql("exec updateProduct @id, @product")
        fail(function(ex, res) { 
            res.statusCode = 500;   
            res.write(ex.message);
            res.end();
        } )
        .param('id', req.params.id, TYPES.Int)
        .param('product', req.body, TYPES.NVarChar)
        .exec(res);

});

Error handler is a function that gets exception and response output as parameters.

express4-tedious's People

Contributors

jocapc avatar v-zhzhou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

express4-tedious's Issues

Express "write after end" on error in SQL query

If the SQL query errors, the default error function "fnOnError" ends the request (called from line 59). After the request is ended, any writes to the request cause an error - for example, line 62.

One fix would be to test for an error in the if statement on line 61.

Azure inserts what appears to be a debug lines before and after the response(s)

Really weird. Code works fine on a local version of node (with an Azure database back-end).

However, When I switch to a Azure instance of node. It appears to add lines of what I would guess is debugging info.

For a SQL query or a stored procedure that returns one data set, it returns a line that appears to be related to the size of the data, then the expected JSON line, then a line with just the number 0.

For a stored procedure that returns multiple data sets,
for each data set {
it returns a line that appears to be related to the size of the data,
then the expected JSON line,
}
then a line with just the number 0.

handle errors

Hi ,
Please is there any way to handle errors when executing a query, example:

req.query("select * from t_users for json path")
        .into(res, '[]');

Regards.

TypeError: stream.listeners is not a function

Please help, I'm getting this TypeError: stream.listeners is not a function error. I believe I've followed the instructions...

var express = require('express');
var tediousExpress = require('express4-tedious');
var bodyParser = require('body-parser');

var config = {
server : process.env.sqlServer,
userName: process.env.sqlUserName,
password: process.env.sqlPassword,
options: {
encrypt: true,
database: process.env.sqlDatabase
}
}

var app = express();

app.use(function (req, res, next) {
req.sql = tediousExpress(req, config);
next();
});

app.use(bodyParser.text());

app.use('/todo', require('../routes/todo'));

/*
GET task listing.
app.get('/', function (req, res) {
req.sql("select * from todo for json path")
.into(res, '[]');
});
*/

// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found: '+ req.method + ":" + req.originalUrl);
err.status = 404;
next(err);
});

module.exports = app;

NodeJs express4-tedious - Stored Procedure for SELECT to return response as JSON

Couldn't show the response in JSON while using a stored procedure.

I'm using express4-tedious to fetch results. It works fine if I use the select query but if I use the same with the stored procedure I don't know how to bind it in JSON.

The response screen is blank as I couldn't get the results.

var tediousExpress = require('express4-tedious');
var TYPES = require('tedious').TYPES;
var router = express.Router();
router.get('/:id', function (req, res) {
    req.sql("exec GETDataOfEmployee @id")
    .param('id', req.params.id, TYPES.VarChar)
    .exec(res)
});

Any suggestions would be of great help.

Serverless function with tedious4 Express

I can get this code working on a node.js express server ok.

For some reason, I can't get a response when I try to put it in a serverless Azure function...

const createHandler = require("azure-function-express").createHandler;
const express = require('express');
const bodyParser = require('body-parser');
const tediousExpress = require('express4-tedious');

const app = express();
app.use(function (req, res, next) {
    req.sql = tediousExpress({
        "server"  : process.env.sqlServer,
        "userName": process.env.sqlUserName,
        "password": process.env.sqlPassword,
        "options": { 
            "encrypt": true, 
            "database": process.env.sqlDatabase 
        }
    });
    next();
});

app.use(bodyParser.text()); 

app.use(function (req, res) {
    req.sql("select * from todo for json path")
        .into(res, '[]');
});

module.exports = createHandler(app);

URGENT Adding token and checking password for login

Hi

I am calling store procedures and right before I use into(res) which sends the response. I want to fetch the user id from the response json received from the SQL query and then create and attach jwt token with response body or header before sending it.

I also want to know how to store result that I get from req.sql into variable and not directly into res so I can use to check password using bcrypt.

console.write is not a function

TypeError: console.write is not a function
at Request.userCallback (C:\Users\mike\Source\Repos\NodeExpressAzureBasicTest\NodeExpressAzureBasicTest\node_modules\express4-tedious\index.js:65:45)
at Request._this.callback (C:\Users\mike\Source\Repos\NodeExpressAzureBasicTest\NodeExpressAzureBasicTest\node_modules\tedious\lib\request.js:60:27)
at Connection.endOfMessageMarkerReceived (C:\Users\mike\Source\Repos\NodeExpressAzureBasicTest\NodeExpressAzureBasicTest\node_modules\tedious\lib\connection.js:1906:20)
at Connection.dispatchEvent (C:\Users\mike\Source\Repos\NodeExpressAzureBasicTest\NodeExpressAzureBasicTest\node_modules\tedious\lib\connection.js:992:38)
at Parser. (C:\Users\mike\Source\Repos\NodeExpressAzureBasicTest\NodeExpressAzureBasicTest\node_modules\tedious\lib\connection.js:813:18)
at emitOne (events.js:116:13)
at Parser.emit (events.js:211:7)
at Parser. (C:\Users\mike\Source\Repos\NodeExpressAzureBasicTest\NodeExpressAzureBasicTest\node_modules\tedious\lib\token\token-stream-parser.js:54:15)
at emitOne (events.js:116:13)
at Parser.emit (events.js:211:7)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.