Need to call Express like use route using Restify - node.js

Expresss.use() accepts 2 parameters
app.use('/abcd', routeHandler);
Restify only supports one
restify.use(routeHandler);
Referring to workaround on https://github.com/restify/node-restify/issues/289
server.use(scopeMiddlewareTo('/prefix', myMiddleware));
I'm trying to use this workaround, but getting below error
{"code":"InternalError","message":"middleware.call is not a function"}
I'm using Typescript, but even the JS code while debugging and middleware.call() is not found.
Basically I have routes in separate files and do not wish to use restify.get(), restify.post() in main.ts. The separate files act as sub-apps.

You can use this package https://www.npmjs.com/package/restify-prefix-route.
var applyPrefix = require('restify-prefix-route');
server.pre(applyPrefix('/v1'));
use this to add prefix in all routes.

Related

How to get all the routes in an adonis jakefile?

I am tring to write a jakefile in adonis framework, which can iterate over all the routes defined in routes.js file.
I am not sure, if the command adonis route:list can be used in any way in the jakefile itself.
You can run adonis route:list in your Jakefile using jake.exec or jake.createExec
var ex = jake.createExec(['adonis', 'route:list']);
ex.addListener('stdout', (msg, code) => console.log(msg));
jake.exec documentation: https://jakejs.com/#running-shell-commands-jake-exec-and-jake-createexec-
The route:list command is defined in https://github.com/adonisjs/adonis-cli/blob/develop/src/Commands/RouteList/index.js. Browsing this file could help you understand how it achieves this action.

How to exclude only 1 endpoint from the list of endpoints in app.js?

These are the links-
app.get('(/api/v1)?/abcd', abcd.get);
app.post('(/api/v1)?/efgh', efgh.post);
app.get('(/api/v1)?/hijk/:item', hijk.get);
app.get('(/api/v1)?/lmno', lmno.getMulti);
app.delete('(/api/v1)?/pqrs/:item',pqrs.delete);
I want to add app.use() for all the links excluding app.get('(/api/v1)?/abcd', abcd.get);
Express middleware's get executed in the order you define them and therefore, you can simply do something as below to make sure middleware code you want is not executed for specific endpoint:
app.get('(/api/v1)?/abcd', abcd.get);
app.use(<middleware_func>);
app.get('(/api/v1)?/hijk/:item', hijk.get);
app.get('(/api/v1)?/lmno', lmno.getMulti);
app.delete('(/api/v1)?/pqrs/:item',pqrs.delete);

nodejs include required packages in all route files using require() function

Hi I'm new to nodeJs and currently developing a Rest API using node.I'm planning to develop it with a good folder structure, so I can scale it up easily. There I'm using several route files according to the business logic.
ex :- authRoutes,profileRoutes,orderRoutes ......
Currently in every single route file I had to include following codes
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var passport = require('passport');
My problem is , Is it totally fine to use above code segments in all the route files( I'm concerning about the code optimisation/coding standards and execution speed ) or is there any better way to do this.
It's better if you can explain the functionality of require() function.
Thanks
In my experience, this is very standard to do. I suggest reading this question and answer to learn more about the way it affects the speed of your programs.
TL;DR of require()
When your lines of code are ran that include a variable that exists because of a require(), for instance
var https = require('https');
https.get(url, function(response) {...});
The compiler reads it and goes into the https module folder, and looks for the .get function.
However, if you are trying to require() a certain JavaScript file, such as analysis.js, you must navigate to that file from the file you are currently in. For instance, if the file you want is on the same level as the file you are in, you can access it like this:
var analysis = require('./analysis.js');
//Let analysis have a function called analyzeWeather
analysis.analyzeWeather(weather_data);
These lines of code are a little different from above. In this require() statement, we are saying grab the .js file with this name, analysis. Once you require it, you can access any public function inside of that analysis.js file.
Edits
Added require() example for .js file.

Moving route logic out of app.js

I'm designing an app with node.js and Express, and I was wondering if it was possible to move certain routing logic out of the app.js file. For exapmle, my app.js currently contains:
app.get('/groups',routes.groups);
app.get('/',routes.index);
Is there a way to move this logic out of the app.js file, and only have something like:
app.get('/:url',routes.get);
app.post('/:url",routes.post);
such that all GET requests would be processed by routes.get and all POST requests processed with routes.post?
You could pass a regular expression as the route definition:
app.get(/.+/, someFunction);
This would match anything. However, if you simply want to move your route definitions outside of your main app.js file, it is much clearer to do something like this:
app.js
var app = require('express').createServer();
...
require('routes').addRoutes(app);
routes.js
exports.addRoutes = function(app) {
app.get('/groups', function(req, res) {
...
});
};
This way, you're still using Express' built-in routing, rather than re-rolling your own (as you'd have to do in your example).
FULL DISCLOSURE: I am the developer of the node module mentioned below.
There is a node module that does kind of what you're asking for (and will, eventually, do more). It offers automatic routing based on convention over configuration for express. The module name is honey-express, but is currently in alpha development and not yet available on NPM (but you can get it from the source at https://github.com/jaylach/honey-express.
A short example of how it works: (Please note that this coffeescript)
# Inside your testController.coffee file. Should live inside /app/controllers
honey = require 'honey-express'
TestController = new honey.Controller
index: ->
# #view() is a helper method to automatically render the view for the action you're executing.
# As long as a view (with an extension that matches your setup view engine) lives at /app/views/controller/actionName (without method, so index and not getIndex), it will be rendered.
#view()
postTest: (data) ->
# Do something with data
Now, inside your app.js file you just have to setup some simple configuration:
# in your app.configure callback...
honey.config 'app root', __dirname + '/app'
app.use honey.router()
Now anytime a request comes in, honey will automatically look for a controller with the specified route, and then look for a matching action.. for example -
/test will automatically route to the index/getIndex() method of
testController
/ will automatically route to the index/getIndex() method of the homeController (the default controller is home), if it exists
/test/test will automatically route to the postTest() method of testController if the http method is POST.
As I mentioned, the module is currently in it's alpha state but the automatic routing works wonderfully and has been tested on two different projects now :) But since it's in alpha development, the documentation is missing. Should you decide to go this route, you can look at the sample I have up on the github, look through the code, or reach out to me and I'd be happy to help :)
EDIT: I should also note that honey-express does require the latest (BETA) version of express as it uses features that are not present in 2.x of express.

Including a .js file in node.js

I am trying to include this script in my app: http://www.movable-type.co.uk/scripts/latlong.html
I have saved it in a file called lib/latlon.js, and I am trying to include it like this:
require('./lib/latlon.js');
How should I go about including a JS library like this?
First of all, you should take a look at the Modules documentation for node.js:
http://nodejs.org/docs/v0.5.5/api/modules.html
The script you're trying to include is not a node.js module, so you should make a few changes to it. As there is no shared global scope between the modules in node.js you need to add all the methods you want to access to the exports object. If you add this line to your latlon.js file:
exports.LatLon = LatLon;
...you should be able to access the LatLon function like this:
var LatLonModule = require('./lib/latlon.js');
var latlongObj = new LatLonModule.LatLon(lat, lon, rad);

Resources