client-side url mapping - javascript

I'm using express and I'd like to clean up my hard-coded URLs. There seem to be a number of projects which produce urlFor functionality on the server-side. Is there a best practice for doing this on the client-side?

Will something like this work for you?
https://gist.github.com/4108452

I ended up building a shared module which exports two functions: pathRaw, and pathFor.
pathRaw outputs a path which can be consumed by the express routing mechanism. For example:
pathRaw('user.video.new');
returns '/users/:userid/videos/new'. Note that I'm using the pluralization functionality from mongoose.
pathFor takes the output from pathRaw and replaces the ids. For example:
pathFor('user.message.index', {userid: 'u1'});
returns '/users/u1/messages'. Note that additional values are converted to query parameters.
There are a few other features like path overrides that I've added. I'll probably put this up on github once the code is a little more battle tested.

Related

NestJs: Is there a way to generate a resource, already wired to a TypeOrm entity?

I'm playing around with NestJs, for the purpose of automating REST API creation as much as possible. So far, I do not see any quick way to create a fully functional resource.
For example, if I use the Nest CLI like this:
nest g resource
And call my resource "posts", I get a module, a controller, a service, dto's and an empty entity
In order to make it functional, I would need to manually go through every method of the PostsService, remove the placeholder, and wire it to the corresponding entity method. For example, this needs to be altered:
findAll() {
return `This action returns all posts`;
}
to:
findAll(){
return this.postsRepository.find()
}
Not to mention, that I need to add various decorators and imports. In my opinion, this undermines the whole idea of CRUD generator. A lot of files are created for me, but they need to be altered.
Is there any way in Nest to create a fully functioning resource(of course i would still need to manually set the fields of the entity), with all parts wired to each other correctly?
I also tried to find something similar. And this is the best what I found https://github.com/ashinzekene/generator-nestjs-app
I think if such a thing existed, then it should have been mentioned in this repository. https://github.com/nestjs/awesome-nestjs
But it's not. Maybe I'm wrong 😑
The purpose of nest isnt to get up and running asap -> You would probably want to use something a little bit more user friendly / or one with a more guided workflow.
in terms of what the generator is giving you...
Controller Only deals with the request / response being recieved and sent... it doesnt have any other type of functionality...
DTO think of it like an interface but with more functionality , as you can add data-validation / etc to make sure the request object is formated properly...
Service Exposes the methods that contain all of our business logic. for a crud app, this would be where your actual get post put patch delete would be ... and how the data us modified in your db. Then once this finishes it would return the response if any to the controller which sends the info out.
this is helpful for many reasons... one if our project has 200 endpoints and 40 people working in different teams you dont want each team to have a different way of doing things, also you want it to be clear where each thing is... if you endpoints need to be changed , you simply go to your controller... if the logic needs to change, you go to that service etc...
The Purpose of nest is to give you a framework for extremely modular apps / essentially everything decoupled..
think of it in terms of an express... you could have a single page express app that just has everything in one place... or you could have every single thing on it's own area...
esentially nest doesnt do anything crazy that express cant, it's just the underlying inversion of control (the .main file which calls the app.module which builds all the different pieces that are needed for that endpoint / app / service / or etc.)
If you just want to use nest because it seems shiny , id consider looking up something like fastify or / even appsmith / or something else like that...

Have multiple URIs with parameters in routes.js using MEAN

I want to be able to use get methods in my MEAN API, i have the following code in my index.js:
router.route('/platillos/:id')
.get(PlatilloCtrl.getPlatillosById)
.post(upload.array(),PlatilloCtrl.addComentario)
.put(upload.array(),PlatilloCtrl.updatePlatillo)
.delete(PlatilloCtrl.deletePlatillo);
and I made this one too:
router.route('/platillosC/:categoria')
.get(PlatilloCtrl.getPlatillosByCategoria);
I would like to have the category and the id in the same URI withouth having an extra one.
Is there a way to do this?
Without knowing exactly what you're using in terms of a routing solution, most libraries will accept and parse multiple parameters, ie:
router.route('/platillosC/:id/:categoria')

Gulp task to translate JS

I'm working on a JavaScript app and have so far entered all my strings as plain text.
This is starting to feel really hacky (I'm used to gettext) so I'd prefer to wrap them all in something like {{translatable_string}} and have a gulp task just search/replace them all during the build step.
So, my question is; is there a generic (no framework-specific like angular-gettext or something like that) gettext replacer out there?
Obviously it doesn't even have to be connected to JavaScript in any way, you should be able to run it on any file type and have {{translatable_string}}:s be translated.
You may want to look into using gulp-replace. As they explained in this answer, you should be able to use it to find and replace any string that you want in the stream.
I suggest a database of strings for your translations if dynamic generation of page content is possible for your app. Starting with English or whichever is normal but the need to localize content is a tough issue without a robust system. A simple MongoDB table can be used to store the content, and when the app needs an interface it can be loaded with the right localized strings. As a for instance:
if(err) alert("Please turn off caps lock");
could become:
if(err) alert(Please_turn_off_caps_lock.English);
If you are needing to build static pages with gulp, a database in conjunction with gulp-replace sounds interesting. Using gulp-data to call up and package the strings, you can then feed it to gulp-replace and alter the files. The extensible nature of databases or document stores enable you to expand your localization without hacking on individual files or trees all the time.
Try gulp-gettext-parser.
var gettext = require("gulp-gettext-parser");
var rename = require("gulp-rename");
gulp.task("gettext", function() {
return gulp.src("src/**/*.js")
.pipe(gettext())
.pipe(rename("bundle.po"))
.pipe(gulp.dest("dist/"));
});
Perhaps what you need is mustache.js, take a look: https://github.com/janl/mustache.js/
I'm not used to work with mustache, but I had to do some updates in a project done with it, and I was surprised the capabilities it have.
If you're familiar with jade (now renamed to pug), you'll find is something similar but at the end, you're not forced to generate only html files, you cand generate any kind of text file.
This blog could be helpful to understand the differences between some other templating languages over Nodejs: https://strongloop.com/strongblog/compare-javascript-templates-jade-mustache-dust/

Best way to pass server (c# / Razor) values into an AngularJS app

We use DNN and often need to pass a few context specific values (like page id or module-on-page-id) into an AngularJS app. We've developed our own conventions how to do this, but would like to hear from others how they approach this to find a best practice.
So basically the situation is that the server-page has information needed by the JS. Using WebAPI is not an option, as these values are known in the page, but not in a separate request. Things I've seen so far have been:
Use in-view-razor like href="#Tab.TabId/{{...}}" (I don't like this)
Place the values in the ng-init like ng-init="config = { prop1: '#Tab.TabId' }"
Create a separate <script> tag where we generate a module on the fly containing these values so angular.module("config", []).constant('prop1', '#Tab.TabId')
Create a json with razor in the page somewhere and inject all of it as a module into the app using a generic code which does the same as #3, just with cleaner code re-use.
I've seen all these and have also used all. Currently we avoid #1 as we believe it's not good to mix templating languages and because it doesn't allow externalizing parts of the view. So basically we use #2 as for quick-and-simple (and a bit dirty) + #3/#4 for larger projects.
Do you have a better way, or which way would you prefer?
We are using variant #4.
This has the advantage that the JSON defines the exact interface for the config needed by the JS module. And Razor is great to generate URLs using #Url.Action.
we use NewtonSoft and do JSONConvert.SerializeObject(ObjectName) and then pass it over as a Session from the controller and then use #Html.Raw(ObjectName) and its a JSON Object that can be utilized easily in javascript...

Proper way to interpolate JSON in Express/Jade?

It seems like this is a solved problem in older frameworks (Django, Rails), but I can't for the life of me find a solution in Express.
A super common pattern in one-page webapps is to use template data to create html and then echo the same data as JSON to the client so that it can maintain state.
each comment as comments
div= comment
script.
var comments = !{JSON.stringify(comments)}
Obviously this isn't safe because a user could easily create a comment that closes the script tag and performs all kinds of nastiness. What's the proper way to deal with this then?
I've seen people claim you can get by with just
JSON.stringify(comments).replace(/<\//g, '<\/')
but that seems naive especially when working with large, forgetful teams.
Similarly, I wrote a function that html escapes recursively before stringifying, but replacing " with " in every string seems like overkill and bad for data binding.
EDIT
For reference, here's Django's solution https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs
If I understand you correctly, you're asking how one might sanitize user input to prevent content injection attacks, XSS, etc.
There are at least three existing Express middleware packages you can take a look at for this sort of thing. express-validator has some sanitization features. It in turn uses node-validator. The current version of node-validator does not do XSS sanitization, so see express-sanitizer below.
The much-beloved helmet middleware has some XSS protection stuff that might meet some or all of your needs. If you are writing an Express app and at all concerned about security, you should definitely checkout helmet if you don't already know about it.
There is an Express middleware modulecalled express-sanitizer. It appears to be recent and only have one contributor, so check the code to see if it meets your needs and seems mature. But it is trying to do XSS sanitization now that node-validator does not do that anymore. (See express-validator above.)

Categories

Resources