I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions get(), save(), all() and count() available to the client. Additionally, it would be great to have the field list of the model already available in the generated JavaScript object.
Whether the current user can read or write the records is a separate issue I will deal with using Django's authentication. For the time being, retrieval would be a start.
In short, is there code that would generate a JavaScript model from a Django model?
Thanks.
It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the methods) but you'd need to expose a web service that can handle every kind of DB-API call. I can't even begin to imagine where to start and the security issues may be too numerous to easily overcome.
The alternative (and much simpler) approach would be to use one of the various Django REST modules and JSON serialization. You could perform an AJAX GET request on a resource, which can be identified by a series of query parameters that would be equivalent to chained queryset filters. This would return the JSON representation of the model's values. You can then modify the JavaScript object and use an overloaded AJAX POST request to persist the changes back to the server. You wouldn't have access to the model's methods, so that functionality would have to be reimplemented but making any changes to a model should be straightforward enough - This is basically the JavaScript equivalent of using an HTML form to modify data.
You need a data serializer. You can do it with django built in serializers. It is documented on official django site. djangoproject_topics-serialization
I've started a project that I think does exactly what you're looking for. You can find it at
github_bumby_jslib. It currently only supports get(), but I'm hoping to extend this soon. Feel free to contribute patches :)
jslib is a Django application aiming to simplify AJAX integration with your Django projects.
It sounds like you want to JSON encode your object data. See JSON.org for more on the data format.
So it's been a while since I posted the original question and since then there has been a number of developments in Djangoland. Not least of which is a great little library called Django REST Framework. I will be using it on a new project and it's looking pretty kewl.
http://www.django-rest-framework.org
Related
The question may seem voluminous - but in order to understand the essence in a different way, it seems extremely difficult to formulate it.
While reading the documentation and some other sources, I encountered a certain misunderstanding related to the variety of file types for interaction when working with the database:
.dao
.dto
.entity
.repo
Question:
How do these types of files differ conceptually in terms of functionality?
(If anyone has a detailed video or article on this topic, I will also be grateful for the link.)
There is also this microproject (working code) taken from the docks:
https://github.com/Mike-Kharkov/nest-perfect-goods/tree/master/src
What should the code for entering values into the database look like?
(what should be the name of this file, where should it be located from the point of view of the approach, and what specific code should be written there?)
For example, if I need to parse data (as I understand it from another service, it is correct to do this in this framework) and then put it in the database without a request via HTTP, then how to do it most correctly from the point of view of the approach?
P.S. I would be grateful for any constructive advice ..
.dao, .repo, and .entity are all pretty much the same thing. They're the ways that you define to talk with your database. There's a little give and take on the definition of the file, .entity is more of defining the table/entity in the database, but with something like TypeORM the entity becomes a method to talk to the database as well (either through the entity class or the Repository class).
DAO stands for Data Access Object, by the way, and you can read more about it and patterns around it on Wikipedia.
.dto is for Data Transfer Object which is usually the definition of how data is passed between services, or over the wire (incoming request, outgoing response, microservice body, etc). In NestJS we use DTO's for incoming request deserialization and validation, along with outgoing response serialization on occasion.
My api takes query parameters such as "page". This is to limit the number items sent over. I realize you can filter these with ember once they've already been retrieved, but I want this app to scale. This means I can't be receiving large amounts of data over the wire like findAll already does. How would I go about doing this in ember? Where should I put my custom ajax? I still would like to use most of the features ember has like the ability to watch my models.
This sounds like you want pagination support, but lamentably this feature is still not implemented in ember core. However some folks have already created pagination support to work with ember, one very good example is from Toran Billups, have a look here: https://github.com/toranb/ember-pagination-example. Have also a look here for a good answer explaining it's implementation: Ember pagination full example
Hope it helps.
Perhaps I misunderstand your question, but you can use App.Model.findQuery and pass it query string parameters, which will be sent to your server.
For example: App.Model.findQuery({page: 5, color: 'blue'}). Of course it's up to your API to implement the response to the query params.
See also:
what's the difference between find, findAll and findQuery in ember-data
findQuery source
Just starting to play with breeze.js because of the obvious gains in coding time, i.e. managing to access model data from the server direct within Javascript (I am a newbie here, so obviously bare with!).
In the past I have used the stock ajax calls to get/post data to the server, and I have used a few different client tools in the past to provide some help in querying local data, such as jLinq.
My question is this. Isn't it dangerous to have essentially full model query access in Javascript? I must be missing something because it looks like a really well thought through tool. In the past I have at least controlled what can be sent to the client via the backend query process, and again using something like jLinq etc I could filter the data etc. I can also understand the trade-off perhaps with gaining the direct query/none-duplicating local model problem, so just if anyone could provide some insight to this?
Thanks!
EDIT
Obviously I am not the only one, however I am guessing there is a reasonable response - maybe limiting the data being requested using DTO methods or something? The other question posted is here
It can be dangerous to expose the full business model. It can be dangerous to allow unrestrained querying of even that part of the model that you want to expose to the client. This is true whether you offer an easy-to-query API or one that is difficult to query.
That's why our teams are careful about how we construct our services.
You should only expose types that your client app needs. If you want to limit access to authorized instances of a type, you can write carefully prescribed non-queryable service methods. Breeze can call them just fine. You don't have to use the Breeze query facilities for every request. You'll still benefit from the caching, related-entity-navigation, change-tracking, validation, save-bundling, cache-querying, offline support.
Repeat: your service methods don't have to return IQueryable. Even when they do return IQueryable, you can easily write the service method to constrain the query results to just those entities the user is authorized to see.
Fortunately, you can blend the two approaches in the same service or in collaborating services.
Breeze gives you choices. It's up to you to exercise those choices wisely. Go out there and design your services to fit your requirements.
Breeze isn't meant to be your business logic in that sense. Keeping in mind the rule of thumb that if you do something in Javascript, anyone can do it, you ought to be restricting the visibility of your own service data as needed.
In other words, it's useful for you if you meant to make the data publicly visible anyway. But only expose the entities that you're happy exposing and allowing anyone to query; another way to look at it is that your API becomes a public API for your website (but not one you advertise and tell everyone to use).
I am personally not a fan of doing things this way as there is a dependency created on the schema of the backend implementation. If I want to make changes to my database tables, I now have to take my Javascript into consideration. I also lack in terms of integration and unit testing.
However, it can have its uses if you want to quickly build a website feature on non-sensitive data without having to build the service methods and various layers of implementation of it.
What about when you expose the Metadata? Isn't that considered dangerous. IMHO is not safe to expose metadata from the DbContext. I know you can construct metadata on the client, but the point is to do things as quickly as possible(if safe).
I've been looking at JavaScriptMVC, and I'm pretty interested in the idea. I'm wondering, though, if there are any ORM solutions for such an architecture. It seems like you will end up having to write two data access layers, one server side to fetch items from the database and one on the client side to retrieve items via AJAX.
My question is, are there any existing (preferably open source) solutions that would let me define a model (XML or class definition) and generate a REST api for me to access my data. I've been looking at DataMapper while I'm thinking about this, and it would be great if create a model, and instead of calling Person.all(:age.gt => 30) like I would in ruby I could just query /Person/All/?filter="age>30" (properly escaped of course) and get back an object serialized to XML without having to write the controller myself.
Is there anything out there like this? Does this seem like an intelligent way to go about framing a javascript based app?
After some more research, I think I've found my answer. Using CouchDB I can have all of the application logic running in the clients browser and use the built in REST api to persist the data to the server. This way, I could even manage the model in the client side javascript.
I'm looking for (arguably) the correct way to return data from a XmlHttpRequest. Options I see are:
Plain HTML. Let the request format the data and return it in a usable format.
Advantage: easy to consume by the calling page.Disadvantage: Very rigid, stuck with a fixed layout.
XML. Let the request return XML, format it using XSLT on the calling page.Advantage: the requested service is easily consumed by other sources.Disadvantage: Is browser support for XSLT good enough?
JSON. Let the request return JSON, consume it using javascript, render HTML accordingly.Advantage: easier to 'OO-ify' the javascript making the request. Disadvantage: Probably not as easy to use as the previous two options.
I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons.
While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?
If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works.
If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a proxy to provide the information in JSON or HTML too, but having XML as the main source is definitly worth the time and effort while building the app.
Like #John Topley said: it depends.
I'd agree with John Topley - it depends on the application. There's a good article on quirksmode that discusses the advantages and disadvantages of each format that you might want to read: http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html
I think this sort of depends on the level of "ajaxyness" your app is going to have. If your front end is a "rich client", al'a gmail, I'd go with the JSON solution, as you'd have to solve the problem of having client side view generation anyway. If you're using ajax sparingly, to provide simple messages to the user, update a few fields now and then, etc, then I'd go with option 1, since most of your view logic is already on the server.
I think trying to use XmlHttpRequest will be a huge headache, unless its the type of headache you don't mind - to do it properly you're almost reinventing the wheel. Then again, people like to reinvent wheels in their spare time, just to say, "Hey, I did it". Not me...
I would get a framework like prototype or Extjs, that has alot of data loading functions built in for XML and JSON, plus you'll get more predictable results, as the frameworks have event handlers to make sure your XmlHttpRequest succeeded or failed. Plus you get support for all the various browsers.
Different response format shouldn't be difficult to produce.
JSON works best for me, i like to keep OO in js, and don't know how to parse XML well :)