1
+ var Connection = require ( 'tedious' ) . Connection ;
2
+ var Request = require ( 'tedious' ) . Request
3
+ var TYPES = require ( 'tedious' ) . TYPES ;
4
+
5
+ const executeSQL = ( context , verb , entity , payload ) => {
6
+ var result = "" ;
7
+ const paramPayload = ( payload != null ) ? JSON . stringify ( payload ) : '' ;
8
+ context . log ( payload ) ;
9
+
10
+ // Create Connection object
11
+ const connection = new Connection ( {
12
+ server : process . env [ "db_server" ] ,
13
+ authentication : {
14
+ type : 'default' ,
15
+ options : {
16
+ userName : process . env [ "db_user" ] ,
17
+ password : process . env [ "db_password" ] ,
18
+ }
19
+ } ,
20
+ options : {
21
+ database : process . env [ "db_database" ] ,
22
+ encrypt : true
23
+ }
24
+ } ) ;
25
+
26
+ // Create the command to be executed
27
+ const request = new Request ( `web.${ verb } _${ entity } ` , ( err ) => {
28
+ if ( err ) {
29
+ context . log . error ( err ) ;
30
+ context . res . status = 500 ;
31
+ context . res . body = "Error executing T-SQL command" ;
32
+ } else {
33
+ context . res = {
34
+ body : result
35
+ }
36
+ }
37
+ context . done ( ) ;
38
+ } ) ;
39
+ request . addParameter ( 'Json' , TYPES . NVarChar , paramPayload , Infinity ) ;
40
+
41
+ // Handle 'connect' event
42
+ connection . on ( 'connect' , err => {
43
+ if ( err ) {
44
+ context . log . error ( err ) ;
45
+ context . res . status = 500 ;
46
+ context . res . body = "Error connecting to Azure SQL query" ;
47
+ context . done ( ) ;
48
+ }
49
+ else {
50
+ // Connection succeeded so execute T-SQL stored procedure
51
+ // if you want to executer ad-hoc T-SQL code, use connection.execSql instead
52
+ connection . callProcedure ( request ) ;
53
+ }
54
+ } ) ;
55
+
56
+ // Handle result set sent back from Azure SQL
57
+ request . on ( 'row' , columns => {
58
+ columns . forEach ( column => {
59
+ result += column . value ;
60
+ } ) ;
61
+ } ) ;
62
+
63
+ // Connect
64
+ connection . connect ( ) ;
65
+ }
66
+
67
+ module . exports = function ( context , req ) {
68
+ const method = req . method . toLowerCase ( ) ;
69
+ var payload = null ;
70
+ var entity = "" ;
71
+
72
+ switch ( method ) {
73
+ case "get" :
74
+ if ( req . params . id ) {
75
+ entity = "customer"
76
+ payload = { "CustomerID" : req . params . id } ;
77
+ }
78
+ break ;
79
+ case "post" :
80
+ payload = req . body ;
81
+ break ;
82
+ case "put" :
83
+ payload = {
84
+ "id" : req . params . id ,
85
+ "todo" : req . body
86
+ } ;
87
+ break ;
88
+ case "delete" :
89
+ payload = { "id" : req . params . id } ;
90
+ break ;
91
+ }
92
+
93
+ executeSQL ( context , method , entity , payload )
94
+ }
0 commit comments