In Meteor.js, what's the difference between method-based database API design and the subclass approach? - meteor

Namely, what are the advantages and disadvantages of the following approaches to building a server-side database API in Meteor?
Method-based
import Db from 'Db';
Meteor.method({"insert": (data) => {Db.insert(data)});
Subclass-based
import {Mongo} from "meteor/mongo";
class MyCollcetion extends Mongo.Collection {
insert: (data) => {super.insert(data);}
}
This problem has been solved below; there is a similar question for further reading: Meteor method vs. deny/allow rules

This is mainly a matter of ease vs control. Subclassing may be easier for simple things, and methods are more powerful.
This can also be affected by your state of mind (or affect it): CRUD vs. action-based mutation.
insert/update/remove go well with a CRUD state-of-mind, while you can associate methods with action-centric RPC mutators.
Eventually, this is a matter of personal preference, so I will try to give a short factual description and let the readers to decide based on their taste.
Subclassing
By default, Meteor automatically generates mutation methods (insert, update, remove) when a collection is instantiated.
Those methods are called behind the scenes when calling MyCollection.insert(mutator, cb) on the client side (outside client-side method code). When arriving to the server, the data are first passed through allow/deny rules and then executed.
When subclassing, you override those methods and get a 'hook' into the process.
Using methods
When defining a Meteor method you get full control of the process.
You set the parameters and the name of the method and you can perform the validation and authorization as you wish.
You can also create a method stub for client-side use, which generates optimistic UI until the results of the method server execution are received.
You can use something like a validatedMethod to get some extra validation logic and modularity to your method.
You can also prevent the creation of the default mutation methods by setting a false value for the defineMutationMethods option when instantiating the collection. You can also forbid direct mutation from the client by supplying the appropriate deny rules.
While subclassing allows you to use MyCollection.insert(...), etc. on the client, you need to call the method name with the arguments that you defined in order to mutate data.

Related

Can I modify a Policy after it is built?

I'm creating an API method call which takes a Policy as an argument.
However, in my method I'd like to 'add onto' this policy by including my own retry Action(s) so that I can perform intermediate logging and telemetry of my own. Similar in concept to adding Click events to a Windows UI control.
Is there a way to modify a Policy after it's created?
Or, is there a hook mechanism where I can define my own callbacks in the Execute method perhaps?
A Polly Policy is immutable; it cannot be modified after configuration. However, there are several ways in which you can attach extra behaviour to a policy.
There could be several approaches depending what you want to achieve.
Note: All examples in this answer refer to synchronous policies / policy-hooks used when executing delegates synchronously, but all the same behaviour exists for the async forms of policies.
Option 1: All policy types do offer delegate hooks such as onRetry; onBreak; onCacheHit, and similar. Extra behaviour (for example logging) can be added in these. The delegates attached to these hooks must be defined at policy configuration time. There are many examples in the Polly readme and Polly-Samples project. The Polly wiki covers all such delegate hooks in depth.
Option 2: If the fact that these delegates (onRetry etc) must be defined at policy configuration time is a restriction: you can overcome this using Polly.Context. Most of the delegates such as onRetry exist in a form which takes Context as an input parameter. That Context is execution-scoped, can carry arbitrary data, and a Context instance can be passed in to the call to .Execute(...).
So you could define Context["ExtraAction"] = /* some Action */ and pass that in to .Execute(...). Then, the onRetry delegate could extract Action extraAction = Context["ExtraAction"] (with some defensive checks) and execute it extraAction(). This allows you to inject arbitrary behaviour to the onRetry delegate after the policy has been configured.
Option 3: Perform your extra logic in the delegate executed. Of course, you could write your own Execute(...) wrapper method which takes a delegate to execute, and a policy, but wraps in extra behaviour.
public TResult MyExecute(ISyncPolicy policy, Func<TResult> toExecute)
{
return policy.Execute(() =>
{
/* do my extra stuff */
return toExecute();
}
}

Where to define record methods in a Redux app

I am building an app with React + Redux + Immutable JS and am running into some architectural problems. To illustrate I will use my user record as an example. The user object is an Immutable Record, defined in the user reducer. Now I would like to define some methods for this user (for example, isCurrentUser(userId), which would return a boolean and can be called on any user instance). From what I gather, the state should simply be plain objects though (reference: How to put methods onto the objects in Redux state?)
However, since this method wouldn't change the state of the application it doesn't make sense to use the typical Redux flow either. Is it acceptable for me to define methods within my Immutable Records, or should I be defining some helper methods in a separate JS file. Or maybe there's something else I haven't thought of?
You can create a new layer called 'services' and put this methods inside it. So, you can have a services/UserSession that is used like.:
{ isCurrentUser } from './services/UserSession'
isCurrentUser(user)
Does it help you?

What is the principle of ractivejs's two way binding?

I'm using ractivejs,I know angularjs's two way binding based "dirty check",but I don't know the principle of ractivejs,who knows?I want a detailed answer.
Ractive doesn't diff or check anything, it uses the declarative template to know exactly what needs to be updated.
Ractive constructs a virtualDOM based on the template. The templated portions of the virtual dom (things with {{...}} in them) register with the viewmodel using the keypaths they contain.
When a ractive.set(...) or one of the other data manipulation methods occurs, dependents are notified of the change (computations and expressions, upstream and downstream keypaths, as well as observers are also notified).
Ractive uses a runloop that batches the actual DOM changes for any set operation to occur at the end of the cycle.
In addition to API calls, Ractive offers twoway binding by default. This maps needed DOM events from form input controls to the API calls to set the data to which it is bound (via the specified keypath).
Ractive does offer the .update(keypath) and .updateModel(keypath) methods which can be used to flush changes from model to view, or view to model when it is not possible for Ractive to know about them, for example using a third-party widget library.

Create AMF wrapper

I am creating a mobile app that will connect to a zendamf implementation to retrive certain information to store and display to the user.
There are multiple php classes on the gateway to handle things like users, Orders, Products etc.
Therefore I would have a package called remotehandler with classes under it, remotehandler.orders remotehandler.product, remotehandler.users. Which would mean for each class I could do the following:
instead of creating a connection for each type of call I want to make lots of times I was thinking that it might be better to create a wrapper class for each call family I.E
Users
createUser - calls a php function to create the user
DeleteUser
UpdateUser
after some searching I came accross this post
http://flexdevtips.blogspot.com/2009/05/using-flex-and-amfphp-without-services.html
which shows how to deal with netconnection in code. but it is written if you are planning on making a single call.
Does anyone have any ideas or example on how I could turn this in to a class that would allow me to specific different source(php class functions).
Thanks
JaChNo
Simply expose a property on your Class (let's call it source) as a getter/setter pair that, when set, changes the source of the RemoteObject.
However, I find it is better to have a different Service Class for each return type I expect, because I can then mock the service and just drop in the mock when I am working on things that don't require a live connection to the database (such as skinning).

Calling a getter without assigning it to anything (lazy loading)

I have a DTO which can be fully loaded or lazy loaded using Lazy Load Pattern. How it is loaded depends on what the Flex Application needs. However, this DTO will be sent to a Flex application (swf). Normally, a collection for instance, will only be loaded when called. In my case however, the collection will only be called in Flex, so my implementation on the .NET side will obviously not work in this case (except if Flex would do a server call... something I would like to avoid).
In the getter of the collection, the data is retrieved from the database. If I would be working with ASP.NET pages, it would work, but not if the DTO is sent to Flex.
How would you deal with this? I could call the getter before sending the DTO to Flex, but that seems awful... + calling the getter can only be done if it is assigned to something (and the local variable that will hold the collection will never be used...).
You can introduce a method to load dependents - loadDependencies - that should take of all lazy loading for your DTO object before being sent over the wire (to Flex). You can abstract this method to an interface to streamline such process across different DTOs. There is nothing against using getters the way you described it inside this method.
I would probably introduce a Finalize method for the class and perhaps a FinalizeAll extension method for various collections of the class. This method would simply go through and reference all the getters on the public properties of the class to ensure that they are loaded. You would invoke Finalize (or FinalizeAll) before sending the object(s) to your Flex app. You might even want to make this an interface so that you can test for the need for finalization before transfering your objects and invoke the method based on a test for the interface rather than checking for each class individually.
NOTE: Finalize is just the first name that popped into mind. There may be (probably is) a better name for this.

Resources