Using constant integers in front and back-end - javascript

Say I have the following constants defined in my back-end API:
User::USER_ROLE_NORMAL; // Equal to 0
User::USER_ROLE_ADMIN; // Equal to 1
In my back-end I can now make the following comparisons:
if($user->role == User::USER_ROLE_NORMAL)
What is the best practice for when I have to apply logic in my front-end? (where these constants are unknown)
It doesn't feel right to hard code the numbers in the front-end, like so:
if(ajaxData.role == 0)
For context: I need to apply logic in the front-end based to change layouts

As frontend and backend logics do not have to be necessarily (and should not be) coupled, the best approach here I think is to define those same constants in the frontend code. Bear in mind that the frontend code should always be in consonance with the API specifications.
The way you do it is up to you (many good alternatives can be found).
An (easy) approach could be with some global variables or using some kind of service if you're using some framework.
Something like:
const role {
USER_ROLE_NORMAL: 0,
USER_ROLE_ADMIN: 1,
};
Then you can use them as follow:
if(ajaxData.role == role.USER_ROLE_NORMAL) {}
Another option (not very used) is that you could create a service in the backend API which provides those values for the frontend to use it. So before the frontend code could use any value regarding to roles (for instance), a request must be made to the backend in order to get those constant values and save it in the frontend in order to use it in future operations.

You could also generate the content of the JS file with all constants using backend. In this way you manage those data in one place, which may be the benefit.

A first solution would be to create another file, for the frontend javascript to use, defining the constants. But this has a big disadvantage: you will have to make sure both files (frontend constants and backend constants) are the same. If you change one, you'll have to remember to change the other.
But firstly, note that this disadvantage also exists if you just hard-code the constants in the first place (this is terrible, and absolutely not an option).
The solution is to have an automated process (the so-called build step of development), that auto-generates the frontend constants file based on the backend constants file.
In javascript development, it's very common to have a build step: Webpack, Grunt, Gulp, etc... If you already have one of those, add to the build step a script that auto-generates the frontend constants file.
If you don't have a build step in your development process, this is a great time to start.

Related

Custom Webpack -- Assign properties to data from Angular Service within Webpack/Write Files based on Angular Template within Webpack

My situation is that I have multiple SVG templates that have data binding on my Angular project, and I want to somehow be able to determine if the data that is going to be bound to these areas is going to fit or not (not get cut off/cover something else basically),somehow mark the products(the data coming in from the angular service) to symbolizes which template it best fits into, or even write/modify the template on an individual product basis and save a copy for each product that I could have the component reference instead.
I am partly able to do this with some basic jquery within the component checking the natural width and height of objects coming into the templates, but it REALLY slows down page load, so it's not viable
I came to the conclusion that I should use a custom webpack to do this, possibly write a loader that analyzes the data coming in from the angular service and figure out which template that specific product fits best. The loader could do the calculations to figure out what fits where.
The reason I want to do this in the webpack is because I ultimately need to do the calculations anyway, and it would really bog down the load time to try and do this much logic dynamically on user load, not to mention it's just redundant in my situation to figure this out more than once, as the product info will not change until the website is updated with a new API call anyway.
I currently have a property hard coded that indicates which template to use(a number corresponding to a template), but doing it this way limits the scope of possible templates, and opens up many possible programmer goofs, as well as the fact that it doesn't cover smaller issues that ARE noticeable, and becoming a problem.
So, my question has three parts:
Is it possible to call an Angular Service/API call in general within a loader.js/ts file?
Can I manipulate the data coming in from an Angular Service/API call and have it preserve those changes (changing a flag property of each product coming in from the service)? The interface in angular that handles the data coming in has an extra property that I could assign potentially in the webpack to denote which template to use.
Could I write html files to a folder on the local project/to a database using that data from a service and the base templates?
I apologize for the wordiness, but the situation has a lot of unique parts that I feel are necessary to include. I don't need code examples so much as I just need to know if Webpack/Loaders can/should even do this. I'm obviously open to any suggestions as well as to other ways to solve this problem.
Notes:
All the code I really have so far for the webpack would be configuring my angular.json to run off of a custom-webpack.config.js file I created, it doesn't currently do anything.
The service executes an http request and is subscribed to by angular components that consume it's data, but I could possibly write a js promise and recreate the interface for the scope of the webpack/loader, which is why I think it may be possible.

ConfigService advantages over dotenv

Is there any advantages (or disadvantages) on using #NestJS/Config instead of using dotenv to retrieve envvar? In both cases I could create a class that is responsible for all envvars, but should I?
I know #NestJS/Config uses dotenv behind the curtains, but is there any reason why one should choose one over the other?
The two big advantages are the ability to use Joi or class-validator or whatever else you want as a schema validator to ensure you have your env values correct to begin with, before trying to access them at runtime and getting an error. Earlier feedback loop means fewer failures later on. The other big advantage is the use of DI meaning it's easier (usually) to mock the env variable value in your test cases, rather than having to assign to process.env itself. There's also slight speed improvements, as Nest caches the value so if you read it again you don't need to read from process.env, but other than that there's not too much to mention. If you don't want to use it, don't feel like you have to. There is also the disadvantage of not being able to use the ConfigService inside a decorator
My understanding is using #nestjs/config is easy for you to manage your config/envvars as a module in your project. So it can be easily swapped in different place:
e.g. if you need a different set of config for test, you don't have to actually modify your process.env.xxx or use a different .env file.
However if you do that, it requires all/most your other services to utilize this pattern as well. It wouldn't be so helpful if you have all your other service to be a pure function export.

How To Encode HTTP parameters with Ruby and Javascript

I'm working on a Rails project with React for the frontend. I want to have some sort of encryption for parameters. For example:
def index
#foods = Food.page(secured_params(:page))
end
secured_params() method is defined in the main ApplicationController of the application.
I want this encryption to be very simple and computational effective. In simple words, it doesn't cause much overhead. With the same technique, the React based frontend should be able to encrypt the parameters' values before they get sent to the backend. On the backend, when it receives the parameters' values, it decrypts and checks if the values are valid. If not, the backend just stops without doing anything. I'm using this technique to avoid bots/crawlers on the Internet.
I found a similar thread on this: https://security.stackexchange.com/questions/17259/better-techniques-than-url-parameter-encryption
In short, people have different techniques. Some do and the other don't follow this approach. If you are on the same side and want to do this, here is one of the approaches: https://security.stackexchange.com/a/63371

Using Angular, where should I store my constants?

This question has less to do with how to do something, but more about best practices and what do others do?
I have a few services where I am using some kind of an external API (in this case the session storage api in the browser), where I am reusing the same constant string, the name of the company and the application, let's call it "ACME.Storage.", and this I want to prepend at the start of every "key" string. I see my options as:
I can just reuse the string "ACME.Storage." in every call.
I can create a JavaScript function where I create a new storage object that is configured with "ACME.Storage." once. That way, "ACME.Storage." appears once in my code.
I can create a local variable ans store "ACME.Storage." in it, then reuse that. Again, the string literal appears only once in my code.
I can create a separate javascript object that I can share.
I can use an AngularJS "constant"
I can add as a field to the app of config file.
I can store it somewhere where localized literal strings (even though this particular string isn't localized) and get it through a translation service.
I'm leaning toward using the "constant" service 'cause it's the one that's easily injectable. My only concern is that it's less encapsulated than some of the other options.
Opinions on the best practice?
To expand upon what Whishler posted, you can (and probably should) use the Constant module that Angular provides. Complete docs are found here: http://docs.angularjs.org/api/ng/type/angular.Module. Services are a common place for constants, but the Constant modules get applied before other provide methods. Another option would be Value, but it does pretty much the same thing.
Generally, I put constants into a service.
Depending what I'm doing, I may create a service that does nothing but store related constants. Or I may add them to another service representing a 'model'.
I'll also add that JavaScript doesn't officially have constants; so unless you wrote some code--such as your own accessors--you're just dealing with a variable that could be changed during the execution.

How to remove JS logging calls in our prod build of our mvc3 web app?

We've got a lot of calls to our logging methods (that just wrap console.log) all throughout our JS in our MVC3 web app and I'd like to remove them from the JavaScript when we build our test and production builds.
Currently we're using the bundling and minification nuget package to bundle and minify our JS into one big minified file but I'd like to have it rip out the calls to the logging methods as well.
We do have a mechanism in place that replaces the logging methods with empty functions so they won't do any work in production, but they are still called and various arguments are passed in. On top of this, there are "large" strings that are passed and those could be removed, reducing filesize.
The ideal solution in my mind would be to somehow parse the JavaScript and detect / remove the calls to those methods. Preferably in some sort of JavaScript engine and not just a regular expression.
Either way, I just want my calls to my logging methods removed in the final JavaScript that is served up in production. Does anyone know how I'd accomplish this additional minification?
Yep, the IBundleTransform interface was designed for this scenario. In RC bits here's what we envisioned:
new Bundle("~/bundles/js", new LogRemoverTransform(), new JsMinify());
Basically, you construct a bundle and chain two transforms, first stripping your log methods, and then running through normal minification. Prior to RC, you would have to do the composition inside of your IBundleTransform.
You could write your own implementation of IBundleTransform that first removes calls to your logging methods via a regular expression and then calls the default bundling and minification functionality. As long as your calls are fairly simple, it shouldn't be hard to come up with. It might get tricky though, depending on how you call your logging code.
For example, it'd be fairly hard (for me) to build a regex that would catch the entirety of a logging call like this:
NS.log(function () { return "this is going to be hard to parse"; }());
But, as long as you don't log like that, it shouldn't be a difficult regex to write.

Categories

Resources