How to set up a nodejs OData endpoint with odata-server

Author: Robert Bonay
19 June 2013

OData, odata-server, nodejs, MongoDB

After your very positive feedback to server-side JayData implementation we decided to help you to create OData-enabled endpoints with much less code by releasing the odata-server npm module.
OData-server module comes handy if want to create a node.js service with standard communication protocols (RESTful OData with XMLS/JSON support). The system comes with an out-of-the-box MongoDB data provider, but you can use SQLite or extend the service with your custom JayData data provider. The beauty of the module is that you can use JayData JavaScript Language Query to manipulate object on the server-side, just as you do with JayData library on the client-side - while writing developer-friendly, pure JavaScript code.

 

We show how will you able to create your CRUD-capable OData endpoint with 4 calls:

 

require('odata-server');

$data.Entity.extend("Todo", {
    Id: { type: "id", key: true, computed: true },
    Task: { type: String, required: true, maxLength: 200 },
    DueDate: { type: Date },
    Completed: { type: Boolean }
});

$data.EntityContext.extend("TodoDatabase", {
    Todos: { type: $data.EntitySet, elementType: Todo }
});

$data.createODataServer(TodoDatabase, '/todo', 52999, 'localhost');

 

Save this code to todo.js.

 

You can use odata-server to publish JavaScript Data Services, which is similar to IQueryable results of WCF Data Services; or JavaScript API Services similar to WCF service methods.

Installing odata-server

The module can be found in npm, so you just have to type the following command:

npm install odata-server

Warming up the odata-server

The module comes with two example services: newsreader and northwind, let’s launch our todo one.
After starting the services with node todo.js   command, the OData endpoint will be published with initialized MongoDB schema, this means you can access your services by opening the following URL in your browser:

  • http://localhost:52999/todo

 

Todo example explained

As a client-side JayData application, server-side services begin with the definition of typed entities. 

 

$data.Entity.extend("Todo", {
    Id: { type: 'Id', key: true, computed: true },
    Task: { type: String, required: true, maxLength: 200 },
    DueDate: { type: Date },
    Completed: { type: Boolean }
});

By defining the Todo this way, the value of the Id field of the object will be generated on the server.

 

(To learn more about JayData visit the Beginners guide to JayData

 

After defining the Todo entity, the second step is to declare the EntityContext to enlist the sets of your entities. As we don’t have multiple objects and object relations, we will have the Todos EntitySet here:

 

$data.EntityContext.extend("TodoDatabase", {
    Todos: { type: $data.EntitySet, elementType: Todo }
});

 

Initializing your todo service takes only two lines of as $data.createODataServer() function encapsulates all the necessary operations based on 4 parameters:

  • Your custom EntityContext
  • The relative URL of the desired service
  • The port to listen
  • The hostname of the service

 

 

$data.createODataServer(TodoDatabase, '/todo', 52999, 'localhost');

 

After starting the service code saved to your todo.js you will have a working OData endpoint, which can be accessed using JayData or any other OData client. Have you ever seen any easier way to set up an OData end-point? Okay-okay, JayStorm PaaS doesn't count! :)

 

The odata-server is compatible with Linux and Windows platforms and you can host it on your own infrastructure or in cloud IaaS like Microsoft Windows Azure or Amazon Web Services.

Try the JayData-powered odata-server now! - https://npmjs.org/package/odata-server

 

Using your todo service

Your todo endpoint can be discovered by typing the http://localhost:52999/todo/$metadata URL to the address bar of your browser.

 

image

 

This is the standard OData metadata descriptor of your endpoint, which enlists all the published types, EntitySets and service methods.

 

After all of this, it’s time to save and query records from a HTML5 client using JayData library.

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://include.jaydata.org/datajs-1.0.3.min.js"></script>
    <script src="http://include.jaydata.org/jaydata.js"></script>
    <script>
        $data.initService('http://localhost:52999/todo').then(function (todoDB) {
            
            //Add new records to the database
            var newTodo = todoDB.Todos.add({ Task: 'Drink a beer', Completed: true });
            todoDB.Todos.add({ Task: 'Buy milk', Completed: false });
            todoDB.saveChanges().then(function () {
                //Id of the saved entity is returned by JayData without manual query
                alert(newTodo.Id);
            })
            .then(function () {
                //query the completed tasks beginning with 'Dri' prefix
                todoDB.Todos.filter(function (t) { return t.Completed && t.Task.startsWith('Dri');})
                    .toArray(function (todos) {
                        console.dir(todos);
                })
            });;
        });
    </script>
</head> 
<body></body>
</html>

 

It’s important to mention that filtering of the records happens on the server by translating the JavaScript .filter() expression to OData query string and JayData parses the results to typed entities, so you can work with results as objects.

 

image

 

This is the time to pose the question of security – how can I authenticate my users and how can I implement authorization? Read Viktor Lázár’s excellent post and learn how to do it yourself using odata-server or try JayStorm PaaS to configure the security using the cloud environment.

 

Stay tuned to see odata-server operating with geospacial data!

Share this

categories: OData, MongoDb, node.js

Leave a comment

comments powered by Disqus