Azure Easy API - can't find documentation for getTable('tableName').insert - node.js

I'm using Azure Easy API on my app service. I'm experimenting a little bit and I can't find proper documentation for this stuff.
When I made a new Easy API, the comments at the top said
// Use "request.service" to access features of your mobile service, e.g.:
// var tables = request.service.tables;
So I went from there to finding out I can add to any of my tables using request.service.tables.getTable('tableName').insert({columnName: value})
I expected .insert() to return a promise, but it doesn't. In fact, it doesn't seem to return anything at all. But I'd imagine it's asynchronous.
And since it doesn't return a promise, my next bet was that it takes a callback, but when I tried .insert({columnName: value}, function(r){response.send(r.toString()}), the entire api just failed to work at all.
How am I supposed to use this .insert function?
And where can I find the documentation to learn this information on my own? Googling is getting me nowhere.

Here is a code sample you can use in your Easy API for inserting a record into the table.
module.exports = {
"get": function (req, res, next) {
req.azureMobile.tables('tableName')
.insert({columnName: 'value'})
.then(() => res.status(201).send('Success!'))
.catch(next);
}
}
The app.js file would have the following content.
// ----------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
// This is a base-level Azure Mobile App SDK.
var express = require('express'),
azureMobileApps = require('azure-mobile-apps');
// Set up a standard Express app
var app = express();
// If you are producing a combined Web + Mobile app, then you should handle
// anything like logging, registering middleware, etc. here
// Configuration of the Azure Mobile Apps can be done via an object, the
// environment or an auxiliary file. For more information, see
// http://azure.github.io/azure-mobile-apps-node/global.html#configuration
var mobileApp = azureMobileApps({
// Explicitly enable the Azure Mobile Apps home page
homePage: true,
// Explicitly enable swagger support. UI support is enabled by
// installing the swagger-ui npm module.
swagger: true
});
// Import the files from the tables directory to configure the /tables endpoint
mobileApp.tables.import('./tables');
// Import the files from the api directory to configure the /api endpoint
mobileApp.api.import('./api');
// Initialize the database before listening for incoming requests
// The tables.initialize() method does the initialization asynchronously
// and returns a Promise.
mobileApp.tables.initialize()
.then(function () {
app.use(mobileApp); // Register the Azure Mobile Apps middleware
app.listen(process.env.PORT || 3000); // Listen for requests
});

Related

Find unused routes or codes in an express app to remove dead code

I have a 4 year old Express project running in production and using Express 4.14. Various developers have kept on adding new features but some old code also remains inside. Is there a way to find unused code- code which is not getting used in a production application ?.
I would like to start by identifying routes that are not being called. We do use logs and logs are ingested in Kibana. We also use APM with Kibana.
Since you log data you can create simple middleware to log every request to your application. After a while (days or weeks, depending on how sure you will feel about this process) you can collect and parse logs to get all requested routes. Then compare requested routes with all routes available in your application and delete unused ones.
The middleware can be as simple as:
// runs for every request
app.use('/', function (req, res, next) {
console.log(`Received request: ${req.method} ${req.path}`);
next();
});
To get all routes registered in your application use this development-only code (inspired by this answer):
console.log(app._router.stack.forEach(middleware => {
if (middleware.route) {
console.log(`${middleware.route.stack[0].method} ${middleware.route.path}`);
} else if (middleware.name === 'router') {
middleware.handle.stack.forEach(route => {
if (route.route) {
console.log(`${route.route.stack[0].method} ${route.route.path}`);
}
});
}
}));

Express JS match route without handling

Given an instance of a Express JS app or router, is it possible to match a request against the apps configured routes and receive a object that describes the route as registered with the app?
For instance, if a request for /users/1 were to be handled by the application, would it be possible for the app/router instance to programatically check if the app has a route that would satisfy this request given the URI and HTTP method?
Desirable sudo(ish) code:
const app = express();
app.use((req, res, next) => {
const handler = app.match(req);
// {
// 'method': 'GET',
// 'path': '/user/:id', <--- mainly looking for this
// 'handler': <function reference>
// }
next();
});
app.get('/user/:id', (req, res, next) => {
// fetch the user and do something with it
});
...
AFAIK there are no publicly documented Express router endpoints that provide the behavior you are describing based on its 4.x Documentation.
However, you could implement this yourself by creating a custom regular expression validator to check if the req.path string matches any defined path. The downside to this is that you would have to maintain that list separately from what is registered to Express, which might prove to be difficult to maintain.
You may be able to root through the internals of the app object to get the functionality you need, but note the instability of that approach will mean your solution could potentially be broken by non-major updates to Express.

How do I access a Azure application setting from inside an Aurelia application?

I have a Aurelia app that I host in an Azure app service. I would like to configure the api endpoint that Aurelia connects to by defining it in a Application Setting. How can I read that setting inside Aurelia?
As the other answers and comments also mentioned, Aurelia runs as a clientside application and has no knowledge of backend-driven applications. So the concept of something like the web.config or appsettings.json is not available here without some serious hacks. You don't want to go there.
That being said, of course you can! :) You can pretty much define any settings file you like, similar to the concept of appsettings.json of ASP.NET (Core) apps but then in Aurelia.
A great example for this is the Aurelia open source plugin Aurelia-Configuration.
Simple instructions are that your first start by adding any .json file you like (like config.json) to your project. Next, register it in your Aurelia startup:
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-configuration'); // <-- there you go
aurelia.start().then(a => a.setRoot());
}
Finally, just read out the values using AureliaConfiguration. The sample below illustrates it with dependency injection:
import {inject} from 'aurelia-framework';
import {AureliaConfiguration} from 'aurelia-configuration';
#inject(AureliaConfiguration)
export class MyComponent {
constructor(config) {
this.config = config;
this.config.get('endpoint');
}
}
The README explains it all.
Note: I'm not affiliated with the aurelia-configuration plugin, but just a fan of it.
Isn't Aurelia a JavaScript client framework, e.g. all-in-browser no backend? Application Settings is a server side thing (key-value store) in App Service. No backend, no app settings.
Consider this restify minimal backend that returns Application Settings by calling /settings/{app-setting-name}:
var restify = require('restify');
function respond(req, res, next) {
// Returns app setting value.
// Provides zero input validation,
// DO NOT COPY PASTE INTO PROD,
// ALL YOUR BASE WILL BELONG TO US.
res.send(process.env[req.params.setting]);
next();
}
var server = restify.createServer();
server.get('/settings/:setting', respond);
server.head('/settings/:setting', respond);
server.listen(process.env.PORT || 3000, function() {
console.log('restify listening...');
});
Hope this all makes more sense now.

Making and changing APIs when online in Nodejs

So were trying to develop an application (or Service) with Node.js that provides each user a custom API that can be called from {theirUserName}.ourwebsite.com. Users will be able to change/edit/remote the endpoints of the API within the application through our editor. They can add params to the endpoints, add auth, etc.
Now my question is, how can we make the API online at first, then how can we change the endpoints online without stopping the API application and running again?
P.S: APIs configuration will be saved into a JSON that will be saved to the DB and once the configuration change an event will be raised that tells us the endpoints have changed.
Using Express, you can add routes after the server is listening, so it's not a problem. Beware of precedence as it will be added at the bottom of the stack.
I would advise to have a db storing routes, and when running the node app (before listening) load all the routes in db and add them to the router. In order to be able to scale your app as well as being able to restart it safely.
Then start listening, and have a route for adding routes, deleting routes, updating routes etc.
Here is a simple example of adding a route after listening :
const app = require('express')();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const someGenericHandler = function(req, res) {
return res.json({ message: 'foobar' });
};
// it creates a route
app.post('/routes', function(req, res) {
try {
const route = req.body;
app[route.method](route.path, someGenericHandler);
return res.json({ message: `route '${route.method}${route.path}' added` });
} catch(err) {
return res.status(500).json({ message: err.message || 'an error occured while adding the route' });
}
});
app.listen(process.env.PORT);
You can try this code, paste it in a file, let say index.js.
Run npm i express body-parser, then PORT=8080 node index.js, then send a POST request to http:/localhost:8080/routes with a json payload (and the proper content-type header, use postman)
like this: { method: 'get', path:'/' } and then try your brand new route with a GET request # http://localhost:8080/'
Note that if you expect to have hundreds of users and thousands of requests per minute, I would strongly advise to have a single app per user and a main app for user registering and maybe spawn a small VPS per app with some automation scripts when a user register, or have some sort of request limit per user.
Hope this helps

configure NodeJS process on two different machine

I have two different nodejs web app running on two different machine.
But I need to have one endpoint to user api1.abc.com/v1 to go one process and api2.abc.com/v2 go to another process.
how can i do this kind of request with the single endpoint to user (abc.com). need a nginx setup guide ?
I need this setup because internally I need to call user authenticated api from one server to another.
On one server you need to receive the data (using express & router):
router.get('/v1', function(req, res) {
// TODO
res.render('something');
});
and on the other you need to fetch:
var express = require('express');
var router = express.Router();
var app = express()
app.use('api1.abc.com', router);
router.post('/v1', function(req, res) {
// process res
});
You can write code at version two apis. In request you can pass version on which you need to call.
Call all api's on version 2. If it required to call on second server. Write code on version one to identify the call from version 2. So that it can by pass the basic authentication.
Thanks,

Resources