OData server with adapter for mongodb and nedb
npm install simple-odata-server⚠️ This repository isn't being maintained. It's stable and still used in jsreport, but we are too busy to provide adequate maintenance. Don't hesitate to let me know if you plan to maintain a fork so I can share it here..
--
js
var http = require('http');
var Datastore = require('nedb');
var db = new Datastore( { inMemoryOnly: true });
var ODataServer = require('simple-odata-server');
var Adapter = require('simple-odata-server-nedb');
var model = {
namespace: "jsreport",
entityTypes: {
"UserType": {
"_id": {"type": "Edm.String", key: true},
"test": {"type": "Edm.String"},
}
},
entitySets: {
"users": {
entityType: "jsreport.UserType"
}
}
};
var odataServer = ODataServer("http://localhost:1337")
.model(model)
.adapter(Adapter(function(es, cb) { cb(null, db)}));
http.createServer(odataServer.handle.bind(odataServer)).listen(1337);
`
Now you can try requests like:
GET [http://localhost:1337/$metadata]()
GET [http://localhost:1337/users?$filter=test eq 'a' or test eq 'b'&$skip=1&$take=5]()
GET [http://localhost:1337/users('aaaa')]()
GET [http://localhost:1337/users?$orderby=test desc]()
GET [http://localhost:1337/users/$count]()
POST, PATCH, DELETE
Adapters
There are currently two adapters implemented.
- mongodb - pofider/node-simple-odata-server-mongodb
- nedb - pofider/node-simple-odata-server-nedb
The mongo adapter can be used as
`js
var Adapter = require('simple-odata-server-mongodb')
MongoClient.connect(url, function(err, db) {
odataServer.adapter(Adapter(function(cb) {
cb(err, db.db('myodatadb'));
}));
});
`
express.js
It works well also with the express.js. You even don't need to provide service uri in the ODataServer constructor because it is taken from the express.js request.
`js
app.use("/odata", function (req, res) {
odataServer.handle(req, res);
});
`
cors
You can quickly set up cors without using express and middlewares using this call
`js
odataServer.cors('*')
`
Configurations
Using existing adapter is just a simple way for initializing ODataServer. You can implement your own data layer or override default behavior using following methods:
`js
odataServer
.query(fn(setName, query, req, cb))
.update(fn(setName, query, update, req, cb))
.insert(fn(setName, doc, req, cb))
.remove(fn(setName, query, req, cb))
.beforeQuery(fn(setName, query, req, cb))
.beforeUpdate(fn(setName, query, req, update))
.beforeInsert(fn(setName, doc, req, cb))
.beforeRemove(fn(setName, query, req, cb))
.afterRead(fn(setName, result));
//add hook to error which you can handle or pass to default
.error(fn(req, res, error, default))
``