Merge pull request #64 from JocaPC/master

NodeJS/JSON sample with documentation updates
This commit is contained in:
Jos de Bruijn
2016-06-22 08:21:47 -07:00
committed by GitHub
14 changed files with 447 additions and 7 deletions
+3 -1
View File
@@ -24,4 +24,6 @@ samples/databases/wide-world-importers/sample-scripts/always-encrypted/PopulateA
*.zip
samples/features/in-memory/ticket-reservations/packages/CircularGauge.1.0.0/CreatePackageFile.bat
samples/features/in-memory/ticket-reservations/TicketReservations/TicketReservations.dbmdl
samples/databases/wide-world-importers/workload-drivers/vehicle-location-insert/MultithreadedInMemoryTableInsert/obj/Release/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs
samples/databases/wide-world-importers/workload-drivers/vehicle-location-insert/MultithreadedInMemoryTableInsert/obj/Release/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs
*.dat
*.sln
+10
View File
@@ -0,0 +1,10 @@
# Samples that use JSON functionalities that are available in SQL Server 2016 (or higher) and Azure SQL Database
[Todo REST API - ASP.NET Core](todo-app/dotnet-rest-api)
This project contains an example implementation of ASP.NET Core REST API with CRUD operations on a simple Todo table. You can learn how to build REST API on the existing database schema using new JSON functionalities that are available in SQL Server 2016 (or higher) and Azure SQL Database.
[Todo REST API - NodeJS/Express4](todo-app/nodejs-express4-rest-api)
This project contains an example implementation of NodeJS REST API using Express4 framework and Tedious. REST API has basic CRUD operations on a simple Todo table. You can learn how to build REST API on the existing database schema using new JSON functionalities that are available in SQL Server 2016 (or higher) and Azure SQL Database.
@@ -1,4 +1,4 @@
# ASP.NET Core REST Web API that uses SQL/JSON functionalites
# ASP.NET Core REST Web API that uses SQL/JSON functionalities
This project contains an example implementation of ASP.NET Core REST API with CRUD operations on a simple Todo table. You can learn how to build REST API on the existing database schema using new JSON functionalities that are available in SQL Server 2016 (or higher) and Azure SQL Database.
@@ -61,7 +61,7 @@ Service uses built-in JSON functionalities that are available in SQL Server 2016
<a name=disclaimers></a>
## Disclaimers
The code included in this sample is not intended demonstrate some general guidances and arhitectural patterns for web development. It contains minimal code required to create REST API, and it does not use some patterns such as Repository. Sample uses built-in ASP.NET Core Dependency Injection mechanism; however, this is not prerequisite.
The code included in this sample is not intended demonstrate some general guidance and architectural patterns for web development. It contains minimal code required to create REST API, and it does not use some patterns such as Repository. Sample uses built-in ASP.NET Core Dependency Injection mechanism; however, this is not prerequisite.
You can easily modify this code to fit the architecture of your application.
<a name=related-links></a>
@@ -70,8 +70,11 @@ You can easily modify this code to fit the architecture of your application.
For more information, see this [article](http://www.codeproject.com/Articles/1106622/Building-Web-API-REST-services-on-Azure-SQL-Databa).
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## License
These samples and templates are all licensed under the MIT license. See the license.txt file in the root.
## Questions
Email questions to: sqlserversamples@microsoft.com.
Email questions to: [sqlserversamples@microsoft.com](mailto: sqlserversamples@microsoft.com).
@@ -0,0 +1,5 @@
node_modules/*
bin/*.dll
obj/*
*.sln
*.log
@@ -0,0 +1,102 @@
# NodeJS Express4 REST API that uses SQL/JSON functionalities
This project contains an example implementation of NodeJS REST API with CRUD operations on a simple Todo table. You can learn how to build REST API on the existing database schema using NodeJS, Express4, and new JSON functionalities that are available in SQL Server 2016 (or higher) and Azure SQL Database.
### Contents
[About this sample](#about-this-sample)<br/>
[Before you begin](#before-you-begin)<br/>
[Run this sample](#run-this-sample)<br/>
[Sample details](#sample-details)<br/>
[Disclaimers](#disclaimers)<br/>
[Related links](#related-links)<br/>
<a name=about-this-sample></a>
## About this sample
- **Applies to:** SQL Server 2016 (or higher), Azure SQL Database
- **Key features:** JSON Functions in SQL Server 2016/Azure SQL Database - FOR JSON and OPENJSON
- **Programming Language:** JavaScript (NodeJS)
- **Authors:** Jovan Popovic
<a name=before-you-begin></a>
## Before you begin
To run this sample, you need the following prerequisites.
**Software prerequisites:**
1. SQL Server 2016 (or higher) or an Azure SQL Database
2. Visual Studio 2015 (or higher) with the NodeJS
**Azure prerequisites:**
1. Permission to create an Azure SQL Database
<a name=run-this-sample></a>
## Run this sample
1. Navigate to the folder where you have downloaded sample and run **npm install** in command window, or run setup.bat if you are on Windows operating system. This command will install necessary npm packages defined in project.json.
2. From SQL Server Management Studio or SQL Server Data Tools connect to your SQL Server 2016 or Azure SQL database and execute setup.sql script that will create and populate Todo table in the database.
3. From Visual Studio, open the **TodoApp.xproj** file from the root directory,
4. Locate db.js file in the project, change database connection info in createConnection() method to reference your database. the following tokens should be replaced:
1. SERVERNAME - name of the database server.
2. DATABASE - Name of database where Todo table is stored.
3. USERNAME - SQL Server login that can access table data and execute stored procedures.
4. PASSWORD - Password associated to SQL Server login.
```
var config = {
server : "SERVER.database.windows.net",
userName: "USER",
password: "PASSWORD",
// If you're on Azure, you will need this:
options: { encrypt: true, database: 'DATABASE' }
};
```
5. Build project using Ctrl+Shift+B, right-click on project + Build, or Build/Build Solution from menu.
6. Run sample app using F5 or Ctrl+F5. /todo Url will be opened with a list of all Todo items as a JSON array,
1. Open /api/Todo/1 Url to get details about a single Todo item with id 1,
2. Send POST, PUT, or DELETE Http requests to update content of Todo table.
<a name=sample-details></a>
## Sample details
This sample application shows how to create simple REST API service that performs CRUD operations on a simple Todo table.
NodeJS REST API is used to implement REST Service in the example.
1. app.js file that contains startup code.
2. db.js file that contains functions that wrap Tedious library
3. todo.js file that contains action that will be called on GET, POST, PUT, and DELETE Http requests.
Service uses Tedious library for data access and built-in JSON functionalities that are available in SQL Server 2016 and Azure SQL Database.
<a name=disclaimers></a>
## Disclaimers
The code included in this sample is not intended demonstrate some general guidance and architectural patterns for web development.
It contains minimal code required to create REST API.
You can easily modify this code to fit the architecture of your application.
<a name=related-links></a>
## Related Links
For more information, see this [MSDN documentation](https://msdn.microsoft.com/en-us/library/dn921897.aspx).
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## License
These samples and templates are all licensed under the MIT license. See the license.txt file in the root.
## Questions
Email questions to: [sqlserversamples@microsoft.com](mailto: sqlserversamples@microsoft.com).
@@ -0,0 +1,15 @@
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.text());
app.use('/todo', require('./routes/todo'));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
@@ -0,0 +1,9 @@
#!/usr/bin/env node
var debug = require('debug')('nodejs_express4_rest_api');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
@@ -0,0 +1,69 @@
function createConnection() {
var config = {
server : "SERVER.database.windows.net",
userName: "USER",
password: "PASSWORD",
// If you're on Azure, you will need this:
options: { encrypt: true, database: 'DATABASE' }
};
var Connection = require('tedious').Connection;
var connection = new Connection(config);
return connection;
}
function createRequest(query, connection) {
var Request = require('tedious').Request;
var req =
new Request(query,
function (err, rowCount) {
if (err) {
throw err;
}
connection && connection.close();
});
return req;
}
function stream (query, connection, output, defaultContent) {
errorHandler = function (ex) { throw ex; };
var request = query;
if (typeof query == "string") {
request = this.createRequest(query, connection);
}
var empty = true;
request.on('row', function (columns) {
empty = false;
output.write(columns[0].value);
});
request.on('done', function (rowCount, more, rows) {
if (empty) {
output.write(defaultContent);
}
output.end();
});
request.on('doneProc', function (rowCount, more, rows) {
if (empty) {
output.write(defaultContent);
}
output.end();
});
connection.on('connect', function (err) {
if (err) {
throw err;
}
connection.execSql(request);
});
}
module.exports.createConnection = createConnection;
module.exports.createRequest = createRequest;
module.exports.stream = stream;
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<Name>nodejs-express4-rest-api</Name>
<RootNamespace>nodejs-express4-rest-api</RootNamespace>
<LaunchUrl>todo</LaunchUrl>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>da18f211-dee4-4b4a-8954-4c7505dc769b</ProjectGuid>
<ProjectHome>.</ProjectHome>
<StartupFile>bin\www</StartupFile>
<SearchPath>
</SearchPath>
<WorkingDirectory>.</WorkingDirectory>
<OutputPath>.</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<ProjectTypeGuids>{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}</ProjectTypeGuids>
<ProjectView>ShowAllFiles</ProjectView>
<NodejsPort>1337</NodejsPort>
<StartWebBrowser>True</StartWebBrowser>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Compile Include="app.js" />
<Compile Include="db.js" />
<Compile Include="routes\todo.js" />
<Compile Include="bin\www" />
<Content Include="package.json" />
<Content Include="README.md" />
</ItemGroup>
<ItemGroup>
<Folder Include="bin\" />
<Folder Include="util\" />
<Folder Include="public\" />
<Folder Include="routes\" />
</ItemGroup>
<!-- Do not delete the following Import Project. While this appears to do nothing it is a marker for setting TypeScript properties before our import that depends on them. -->
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" Condition="False" />
<Import Project="$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>False</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>0</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:48022/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>True</UseCustomServer>
<CustomServerUrl>http://localhost:1337</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}" User="">
<WebProjectProperties>
<StartPageUrl>
</StartPageUrl>
<StartAction>CurrentPage</StartAction>
<AspNetDebugging>True</AspNetDebugging>
<SilverlightDebugging>False</SilverlightDebugging>
<NativeDebugging>False</NativeDebugging>
<SQLDebugging>False</SQLDebugging>
<ExternalProgram>
</ExternalProgram>
<StartExternalURL>
</StartExternalURL>
<StartCmdLineArguments>
</StartCmdLineArguments>
<StartWorkingDirectory>
</StartWorkingDirectory>
<EnableENC>False</EnableENC>
<AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>
@@ -0,0 +1,19 @@
{
"name": "nodejs-express4-rest-api",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"description": "nodejs-express4-rest-api",
"author": {
"name": "Jovan Popovic",
"email": "jovanpop@microsoft.com"
},
"dependencies": {
"body-parser": "^1.15.2",
"debug": "^2.2.0",
"express": "^4.14.0",
"tedious": "^1.14.0"
}
}
@@ -0,0 +1,71 @@
var express = require('express');
var router = express.Router();
var db = require('../db.js');
var TYPES = require('tedious').TYPES;
/* GET task listing. */
router.get('/', function (req, res) {
db.stream("select * from todo for json path", db.createConnection(), res, '[]');
});
/* GET single task. */
router.get('/:id', function (req, res) {
var conn = db.createConnection();
var request = db.createRequest("select * from todo where id = @id for json path, without_array_wrapper", conn);
request.addParameter('id', TYPES.Int, req.params.id);
db.stream(request, conn, res, '{}');
});
/* POST create task. */
router.post('/', function (req, res) {
var connection = db.createConnection();
var request = db.createRequest("exec createTodo @todo", connection);
request.addParameter('todo', TYPES.NVarChar, req.body);
connection.on('connect', function (err) {
if (err) {
throw err;
}
connection.execSql(request);
});
});
/* PUT update task. */
router.put('/:id', function (req, res) {
var connection = db.createConnection();
var request = db.createRequest("exec updateTodo @id, @todo", connection);
request.addParameter('id', TYPES.Int, req.params.id);
request.addParameter('todo', TYPES.NVarChar, req.body);
connection.on('connect', function (err) {
if (err) {
throw err;
}
connection.execSql(request);
});
});
/* DELETE single task. */
router.delete('/:id', function (req, res) {
var connection = db.createConnection();
var request = db.createRequest("delete from todo where id = @id", connection);
request.addParameter('id', TYPES.Int, req.params.id);
connection.on('connect', function (err) {
if (err) {
throw err;
}
connection.execSql(request);
});
});
module.exports = router;
@@ -0,0 +1 @@
npm install
@@ -0,0 +1,42 @@
DROP TABLE IF EXISTS Todo
DROP PROCEDURE IF EXISTS createTodo
DROP PROCEDURE IF EXISTS updateTodo
GO
CREATE TABLE Todo (
Id int IDENTITY PRIMARY KEY,
Title nvarchar(30) NOT NULL,
Description nvarchar(4000),
Completed bit,
TargetDate datetime2
)
GO
INSERT INTO Todo (Title, Description, Completed, TargetDate)
VALUES
('Install SQL Server 2016','Install RTM version of SQL Server 2016', 0, '2016-06-01'),
('Get new samples','Go to github and download new samples', 0, '2016-06-02'),
('Try new samples','Install new Management Studio to try samples', 0, '2016-06-02')
GO
create procedure dbo.createTodo(@todo nvarchar(max))
as begin
insert into Todo
select *
from OPENJSON(@todo)
WITH ( Title nvarchar(30), Description nvarchar(4000),
Completed bit, TargetDate datetime2)
end
GO
create procedure updateTodo(@id int, @todo nvarchar(max))
as begin
update Todo
set Title = json.Title, Description = json.Description,
Completed = json.Completed, TargetDate = json.TargetDate
from OPENJSON( @todo )
WITH( Title nvarchar(30), Description nvarchar(4000),
Completed bit, TargetDate datetime2) AS json
where Id = @id
end
+7 -3
View File
@@ -1,13 +1,17 @@
# Samples for specific SQL Server and Azure SQL features
[In-Memory OLTP](features/in-memory)
[In-Memory OLTP](in-memory)
In-Memory OLTP can significantly improve performance of transaction processing in SQL Server and Azure SQL Database. It is a memory-optimized database engine integrated into the database engine, optimized for OLTP. With In-Memory OLTP you can increase the transaction throughput by up to 30 times, depending on the specifics of the workload.
[Master Data Services](features/master-data-services)
[Master Data Services](master-data-services)
Master Data Services (MDS) is the SQL Server solution for master data management. Master data management (MDM) enables you organization to discover and define non-transactional lists of data, and compile maintainable, reliable master lists.
[R Services](features/r-services)
[R Services](r-services)
SQL Server R Services brings R processing close to the data, allowing more scalable and more efficient predictive analytics.
[JSON Support](json)
Built-in JSON functions enable you to easily parse and query JSON data stored in database, transform relational data to JSON text, and vice versa.