Sequelize: Where should these methods reside - javascript

You have 2 tables:
Users
Accounts
A user can have many accounts.
You need to add an account to a user. Using Sequelize, you can attach an instance method to the User model called addAccount(). But also, if you look at it from a different angle, the Account table is really creating a new record, so the Account model could have a class method called createAccount().
Which is more semantically correct? Or should the solution be a mix of both where you call addAccount() on a user instance and that method calls the class method createAccount() on the Account model?
And considering that this is a node/express app, the information to create the account needs to be validated and then parsed from the request. Where would you make that validation/parsing happen? In the routes before calling the account creation method? Or as a 'private' function (__parseReq) in the class methods of either the User model or the Account model?

If I were in your position, I would prefer to use addAccount on a user instance. The main reason is because by doing so, you can easily say that the newly created account "belongs to" the user instance in question.
Anyway, if (for some reasons) you really need to create an individual account without the presence of a user instance, you can still use Account.create().
For the value validation, you could either manually validate before doing sequelize operations or you could define your validation rules in the model definition (more info here).

Related

Is there any way by which we can create relationship in dynmodb

I am new to Amazon Dynamo DB, I have created a user table and address table.and I want to retrieve all users with their particular address as I have assigned user_id in address table to each address. So how can I get user info with address with one query rather than querying both table and merge after. Is their any way like in MySQL we can use JOIN?
Dynamodb is not meant for these types of queries; especially aggregation queries are not ideal. DynamoDB is mainly good for fast lookups for predefined access patterns (e.g. get all items in shopping cart for user ID X).
Since addresses are unique properties of users, you might be able to add an attribute to the user ID table. So basically you have one table with all user data and their properties, including address, that you can query by user ID.
If you need to support different queries I'd suggest you note them all down first before deciding on your data model. (E.g. get all users and sort by last name, get all users living in city X). If the data model in dynamodb is too complex to support all these access patterns you might need to change to a SQL-like db instead.
Edit: note that there are ways to model relationships in dynamodb but they are not trivial. For some examples see the link below. But as suggested above, first define your access patterns before deciding on your data model.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql-B.html

What's the Flow for Stripe Elements?

I'm switching from PayPal to Stripe so I can keep the checkout system entirely on my own sales site. While I have an intermediate understanding of PHP and API interactions, I'm so jaded from using PayPal for 3 years I can't figure out how the flow works for Stripe. Their documentation is excellent, it's more "Dictionary" like and not actual examples.
I'm looking to sell Subscription payments from my own site. You create the HTML, include the Stripe.js bit, but what's the process itself? As in, "index.php submits the checkout form, which notifies Stripe, which sends a ping back to charge.php..." etc, that sort of thing.
Where does the customer creation go, and how does it get attached to a CC charge?
Where does the confirmation from Stripe go?
Where does my price checking PHP go?
I've emailed Stripe, and while they're friendly enough they more or less just told me to go online to their documentation, which I've already spent hours in and still don't get it.
I know I'm being dumb - the tutorials online all seem to focus on Stripe Checkout, which is the popup that I don't want, not the custom HTML form.
Thanks in advance guys. :)
There are a number of different ways you can set it up. Here's how we do it in our application.
When the user enters CC information, you use the Stripe.js API on the client to submit the CC to Stripe, and it returns a token. The callback removes the CC data from your form, puts the token in a hidden field in the form, and submits the form to the server.
If you want to save the customer's CC information so they don't have to re-enter it every time, you then use the stripe-php API to create a \Stripe\Customer object for this CC, sending the token as the card parameter. This will return a customer ID, you can save this in your user database for future reuse.
To charge the card, you create a \Stripe\Charge object, with this customer ID in the customer field. The response from this indicates that the charge was successful; if there's a problem it will throw an exception.
If you just want to do a one-time charge without saving the CC permanently, you could just go straight to creating the \Stripe\Charge object, and use the token as the source field.
If you want to allow customers to have multiple saved cards, you create the \Stripe\Customer object the first time, and when they add a new card you retrieve their customer object, add the new token to the source array, and update it. Then on future charges you can specify both the customer and source fields. In this case, the source field should be the card ID of one of their saved cards.
You would presumably do your own validation of the form, and calculate the price, before calling the Stripe API from the PHP script.
Stripe do have a section with examples and sort of step by step guides for this, don't know if you found it - its separate to the API documentation and I didn't see it first time round. [https://stripe.com/docs/subscriptions/quickstart][1] [1]: https://stripe.com/docs/subscriptions/quickstart
For this to make sense, you will need to install their client library for PHP (or whatever you're using) and be familiar with PHP forms.
To answer your questions:
Where does the customer creation go, and how does it get attached to a
CC charge?
This is done using the functions from their library, see link above. The customer creation is sort of separate from the charge. You will need to store the customer ID in your database to charge them later.
Where does the confirmation from Stripe go?
This is returned in the response from the api call.
Where does my price checking PHP go?
Not sure what you mean by this. Presumably you work out the price to charge them first with your code, you can then just give this to stripe as an amount.
Hope this helps.

Check for changes in the data of a form without using javascript

I currently have the below javascript to detect changes in my form.
form.addEventListener("input", function () {
ChangesMade = true;
console.log("Change");
});
I now need to include whether or not a change has been made in a call to the controller which means that the value can no long be stored in javascript as this is client side.
You have a couple options...
1. Construct a view model with two instances of your model. One the "original" instance, one the "changed" instance. Bind the "original" fields to hidden inputs in your form, and bind the "changed" fields to your normal form elements.
Then, when the form is posted to the server, your controller action's input would have two instances to compare. If the "changed" values are different from the "original" values, then the user changed something.
Note however that users can still change hidden inputs if they want to. This is not a secure measure, but can be an effective one if "security" isn't a concern here.
2. Keep your view and controller interaction the same as it is, but when the data is posted to the controller you would use the identifier from that record to fetch the original from the database.
Using the posted model and the database-fetched model, compare the two. If values are different then the user changed something.
Note however that this doesn't cover race conditions. It's possible that another user changed the database values since this model was originally shown to this user. You can get around this by adding timestamps of when data was changed, but it might not be enough to tell you what data was changed unless you keep audit copies of old records. The complexity of that escalates quickly.
It's a trade-off between the two options of which one meets the actual needs of the system with acceptable drawbacks.
Send the form data to the server
On the server side load current data from the DB
Compare and test for changes

Meteor facebook id vs accounts id

I am making an application which uses both the accounts package and facebook's graph api. Specifically the friends api. The friends api returns all facebook friends that have used the application. The problem is that it returns facebook id's, and the accounts package generate application specific id's. This is problematic when i want to retrieve information from a collection containing a friends information, but stored with the application specific id. I have worked around this by storing both the fb id and the accounts id in the collection.
But i still can't update a user data based on their fb id, as update is only permitted using the application specific id. What i want, but not allowed:
UserData.update({fbId: friend.fbId},{$push: {some: data}});
The only solution i could think of is to get each user id first, like this:
var friendId = UserData.findOne({fbId: friend.fbId})._id;
This is obviously not a good solution as it needs one extra db call for every update.
Is there a way of setting the accounts id equal to the facebook id upon creation? Or do you have any other suggestions.
Extending on the comment above:
MoeRum: #Xinzz UserData is a custom collection. If try updating with fbId I get the
following error: Uncaught Error: Not permitted. Untrusted code may
only update documents by ID. [403]
That is because you're trying to update on the client-side. You can only update by ID on the client-side. What you're trying to do should not be a problem as long as you do it on the server.
From the Meteor docs (for more reference: http://docs.meteor.com/#/full/update):
The behavior of update differs depending on whether it is called by
trusted or untrusted code. Trusted code includes server code and
method code. Untrusted code includes client-side code such as event
handlers and a browser's JavaScript console.
Trusted code can modify multiple documents at once by setting multi to
true, and can use an arbitrary Mongo selector to find the documents to
modify. It bypasses any access control rules set up by allow and deny.
The number of affected documents will be returned from the update call
if you don't pass a callback.
Untrusted code can only modify a single document at once, specified by
its _id. The modification is allowed only after checking any
applicable allow and deny rules. The number of affected documents will
be returned to the callback. Untrusted code cannot perform upserts,
except in insecure mode.

Setting Backbone Marionette model via Global Object

In a Backbone.Marionette application I'm building, we have an authentication which returns a user object, which we in turn stash at App.User (so it's not truly global).
The problem I'm having is that I don't want to make a call to an API endpoint to access the various properties of the returned user object. The specific use case I'm working through right now is that the returned user object contains data about which modules in the app the user is permitted to access (no worries about security, we've clarified that it's OK that the user can spoof a var in their console to gain access to the UI, the services layer will prevent their actions in such an area from being meaningful).
My goal is to avoid a scenario where every time I need access to users.appAccess (a hypothetical array that lists the modules I can access) in order to instantiate it as a model I have to call out to a URL / API endpoint by declaring it in the collection's definition like this:
Entities.Access = Backbone.Collection.extend({
url: 'http://example.com/users/:id/access/',
}
});
Removing the url property from the above code throws an error, and I can pass it a function which returns empty but this doesn't play nice with
var access = new Entities.Access()
access.fetch();
when attempting to pass the fetched collection to a Marionette CollectionView. Should I simply avoid using the fetch() method and keep it otherwise a typical (albeit hack-ish) Backbone collection definition?
Backbone allows you to populate a Backbone collection either as you have (with an empty constructor) or with a collection of data. It sounds like you've already got the data stored in the User object, and you want to push this information to the Entities.Access collection.
var access = new Entities.Access(user.access);
I'm with you, this feels a bit like a hack, but since Backbone doesn't support this nativly there isn't much else you can do. Have a look at Backbone-Relational or supermodel.js. These projects provide better forms of model nesting than the default implementation.

Categories

Resources