Mongoose ODM, BreezeJS - one model definition - javascript

is there any "ready to you" solution how to export mongoose models to client side app? If I imagine perfect world, mongoose models would let me define which properties and methods of entity is needed on client side and generates needed classes for client so I can easily use them with BreezeJS for example.
Any idea? Or is it road to hell combine it together? :))

Update - As of v 1.2.7 - we have provided two facilities that will help accomplish tasks like this.
The Breeze metadata format has been documented and any json object that adheres to this format and is returned from the breeze metadata call will be used to configure breeze's client side metadata.
The JsonResultsAdapter may be used to reshape or assist with interpreting the result of any web service call so that any results returned by the call can become Breeze entities.
--- Previous post
Please stay tuned, we will be releasing a new version of breeze in the next few days with support for pluggable json adapters that will allow the consumption of any web service. And since breeze metadata can already be defined for an arbitrary model, you should be able to consume your mongoose models pretty easily. Of course, the devil IS in the details.

Related

JavaScript framework and JSON Schemas

I came across this question and was quite baffled. I could not understand the underlying thoughts behind this. I have done some API intergation using AngularJS usng $http and $resource when its RESTFul, but these two questions was something like a puzzle. I want to understand this in detail.
Does the JavaScript framework you choose support a model abstraction
with REST integration? If so, what schema does it expect the JSON
replies to use?
Can anyone explain me the two questions.
Some libraries expect your REST API to return specifically structured result. (HAL, JSONP, HATEOAS, ...)
By default, $resource works best with HAL, but it can easily be extended to support other types of return formats (https://github.com/jmarquis/angular-hateoas)
Maybe the question is asking about something like jQuery.map() which allows you to convert the JSON object from the server to your own internal object (abstracted model).
If you use the object from the server throughout your code, and that object's schema changes (e.g. email string changes to emails array), you may have to change your code in many places. But if you've mapped the server data to a local object, you may only need to change the mapping (e.g. set internal email to first value from server emails).

Search API between client and server in mongodb

I have my server in nodejs and client in angularjs, mongodb(mongoose) as database. I want my client to be able to make a search query with all the normal consitions put in like fixing few fields to certain values, search string contained in few of the fields etc
query can be
(value of field A can be 'x' or 'y') and
(value of field B can range between dates P and Q) and
(string s contained in fields C or D or E) few more
is there any npm plugin or standardisation I can follow to enrich my server side API and also directly put the expression while querying with out doing a map reduce with multiple queries(with lots of code).
Yes, there are a few. I only know of those that work with Mongoose so if you're using another driver you may need to modify them a bit.
With each of these you'll need to determine which to filter locally and which to let the server handle it. Where you filter should depend largely on how much data you have. Personally, it made more sense to abandon local filtering for my largest sets and simply rely on MongoDB to handle the workload.
angoose
Connecting Mongoose and Angular and More
The original motive for Angoose project is to do away with the dual
model declarations(server and client side) if we are building a rich
model based SPA application using modern Javascript framework such as
Angular and node.js. With both front end and backend using Javascript,
Angoose allows the server side models and services to be used in the
client side as if they reside in the client side.
Angoose depends on following frameworks and assumes you have basic
familarities with them:
mongoose
express
angular (optional, for non-angular app, jQuery is required)
Mongoose Api Query
Mongoose plugin that takes a set of URL params and constructs a query for use in a search API. Also, worst project name ever.
If you use Mongoose to help serve results for API calls, you might be
used to handling calls like:
/monsters?color=purple&eats_humans=true
mongoose-api-query handles
some of that busywork for you. Pass in a vanilla object (e.g.
req.query) and query conditions will be cast to their appropriate
types according to your Mongoose schema. For example, if you have a
boolean defined in your schema, we'll convert the eats_humans=true to
a boolean for searching.
It also adds a ton of additional search operators, like less than,
greater than, not equal, near (for geosearch), in, and all. You can
find a full list below.
When searching strings, by default it does a partial, case-insensitive
match. (Which is not the default in MongoDB.)
Angular Bridge
Link models easily via a REST interface between Mongoose/Node-Express/Angular.js
Create, read, update, delete MongoDB collections via AngularJS.
It uses :
Mongoose for accessing to Mongodb
Express for the routing
AngularJS (with the $resource method)

How can I add context metadata to my entities without using EF?

I have to implement an architecture where, unfortunately, we are using SharePoint 2013 as, effectively, our principle database. (Not my choice, in case you hadn't picked that up). I have an Asp.Net MVC facade application on the server, handling composition of data from SP and a couple of other data sources, and then a JavaScript SPA as client. An additional wrinkle is that the client needs to be able to work offline, so I need to use IndexedDB to store the data for offline access.
This seems a perfect use-case for breeze.js. My basic architecture is to define a strongly typed model in the MVC facade that will wrap the untyped data I get from SP (in the form object["property"] - using the SP Client Side Object Model). Breeze will handle synchronization between this model and the client, and I will use the export/import functionality to cache data in IndexedDB as required.
So far so good. But... the SOA examples on the breeze site are still under development (and to me, this is fundamentally an SOA architecture, with each SP List a service to be composed). The closest thing I can find is the NoDB sample but this hard-codes metadata on the client. I'd like to establish relationships and validation in the MVC model, and then pass these through to the client, so validation can run off the same declaration in both places.
Is this possible? If so - how? If not does anyone have a workaround or a better idea? I'm already resigned to defining the model in two separate places (the facade and, implicitly, the structure of the SP lists). I would dearly like to avoid implementing it a third time in the client. I'm open to having breeze.js talk directly to the SP REST endpoints, but my understanding from https://stackoverflow.com/a/15364503/1014822 is that the implementation is flawed and does not expose the required metadata.
Resolution: Based on the accepted answer below, I came to the following solution:
1) Generate a service reference from the SP ListData.svc endpoint - thus creating an edmx and proxy classes.
2) Extend ContextProvider in my Repository and override BuildJsonMetadata like so:
protected override string BuildJsonMetadata()
{
XDocument xDoc = XDocument.Load(HttpContext.Current.Server.MapPath("PATH_TO_EDMX"));
String xString = xDoc.ToString();
xString = xString.Replace("DATA_SERVICE_NAMESPACE", "APP_NAMESPACE");
xDoc = XDocument.Parse(xString);
var jsonText = CsdlToJson(xDoc);
return jsonText;
}
3) Modify breeze.js very slightly, editing line 12383:
var schema = metadata.schema || metadata["edmx:Edmx"]["edmx:DataServices"].schema;
(I could presumably also have fixed this in the ContextProvider by choosing a descendant rather than the root node for my xDoc)
4) - Optionally use #Christoff's very useful T4TS.tt template script to generate a d.ts from the service proxy classes so I can have type safety on the data that breeze loads.
So far so good with this setup - I can perform basic CRUD with metadata, backed by SP as a data source.
As of v 1.2.7, We have documented Breeze's metadata schema, and json objects that adhere to this schema that are returned from your webservice will now be honored by Breeze.
--- previous post below
We are in the process of documenting how to expose arbitrary server side metadata over the next week or so, followed soon thereafter by some examples of how to consume an arbitrary web service. There are a few small code changes involved as well.
For the time being, until these docs are complete, the best workaround is to create your metadata on the client and use a jsonResultsAdapter to shape the results of your service call into "entities". The metadata you create on the client will be exactly the same as the metadata that you will eventually be creating on the server and sending down to the client.
Hope this helps.

Open Source remote / distributed / persistent JSON object library for Python serverside and Javascript clientside?

I'd like to be able to have Javascript code manipulate a persistent JSON object in the browser, and have it synchronise with the server, and other clients in real time.
I'm already using MVC separation.
I'd like to be able to do something like this:
function sendMessageToUser(username, message){
messageID = window.model.userMessages[username].messages.length;
window.model.userMessages[username].messages[messageID] = message;
window.requestModelSync();
}
in this example, window.model is a JSON object that is syncronised periodically or on demand, with errors upon collisions, so 'heavy' client code can handle such an event (it is not caught in the example, but if another user messaged the same user at the same time before syncs occurred, an error might be raised by the sync library).
The view code would be called upon a model change and would re-render the messages for the user - in real time.
Are there any libraries that do this already that are somewhat simple, and open-source?
Assuming it's not so secure, I'd like to add cookie based user authentication and key / value validation to it, assuming it doesn't exist already - while still using JSON, with no schema's or models required to start hacking.
I've seen Robert Sayre's sync.js which could be a key building block but I'd like to see something more fully formed, and preferably in use already. I.E: COMET, collision avoidance / resolution strategies, low bandwidth use etc already implemented.
If it doesn't exist I'd be happy to work on such a plugin with people skilled in Python and Javascript.
I've seen http://persistencejs.org/plugin/sync - it is not JSON, they end up defining their own model class.
I don't want to use something as complex as Apache Wave's API's either. Simplicity for prototyping is a key goal.
Firebase is a good candidate for solving your problem.
There isn't a native Python library, but there is a Python wrapper around the REST API
See:Firebase
Firebase home page

How to assert/unit-test servers JSON response?

My current project uses JSON as data interchange format. Both Front-end and Back-end team agree upon a JSON structure before start integrating a service. At times due to un-notified changes in JSON structure by back-end team; it breaks the front-end code.
Is there any external library that we could use to compare a mock JSON (fixture) with servers JSON response. Basically it should assert the whole JSON object and should throw an error if there is any violation in servers JSON format.
Additional info: App is built on JQuery consuming REST JSON services.
I would recommend a schema for your JSON objects.
I use Kwalify but you can also use Rx if you like that syntax better.
I've been using QUnit: http://docs.jquery.com/QUnit recently for a lot of my JS code.
asyncTest http://docs.jquery.com/QUnit/asyncTest could be used pretty effectively to test JSON Structure.
Example:
asyncTest("Test JSON API 1", 1, function() {
$.getJSON("http://test.com/json", function(data) {
equals(data.expected, "what you expected", "Found it");
});
});
Looks like you're trying to solve a problem from other end. Why should you as a front-end developer bother with testing back-end developer's work?
A JSON that is generated on server is better to test on server using standard approach, i.e. functional tests in xUnit. You could also look at acceptance test frameworks like FITnesse if you want to have tests and documentation wiki all in one.
If even after introducing testing on server you'll get invalid JSON it is a problem in human communication, not in tests.
Since there is no answer I'll put my two cents in.
If the problem is that you are dealing with shifting requirements from the back-end then what you need to do is isolate yourself from those changes. Put an abstraction between the front-end and back-end.
Maybe you can call this abstraction the JSON Data Format Interchange.
So when GUI unit-testing (hopefully you are TDDing your Web GUI) you will have a mock for the JSON DIF. SO when the time to integrate the back-end with the front-end*, any software changes will be done in the abstraction layer implementation. And of course you already have tests for those based upon the agreed upon JSON structure.
OBTW, I think that the server-side team should have responsibility for specifying the protocol to be used against the server.
*Why does this remind of the joke my butt and your face could be twins.
https://github.com/skyscreamer/JSONassert may be helpful in eliminating false positives, so that if the order of fields returned by server changes, but overall response is the same, it doesn't trigger a failure.

Categories