ServerCode Guide

Learn how to deploy and write your own servers.

Introduction

Appstax ServerCode lets you quickly deploy a Node.js application and easily use it as part of your Appstax app or as a standalone API. This guide will show you how to create and deploy your first application and a few scenarios where ServerCode is useful.

ServerCode is currently in private beta and you must provide an access code in order to use it. If you want to be a part of the beta test please inquire for a key using the following email address: support@appstax.com.

Before you begin

In order to write server code you need to

You also need to sign up and create an Appstax app at https://appstax.com/. The app needs to have the ServerCode component enabled.

Preparing your development environment

Start by creating a new folder for your project:

mkdir myapp
cd myapp

Now use the appstax command-line tool to initialize a new app:

appstax init

Follow the instructions to select an app to initialize and then choose the "No template" option. This will create an appstax.conf file and an empty /server subdirectory.

Now create a "Hello World" Node.js server app. Create a app.js file in /server and add this code:

var http = require('http');

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

server.listen(3000, function() {
  console.log("Server running at port 3000");
});

Now try to run this app locally:

cd server
node app.js

Then http://localhost:3000/api should show a page that welcomes you to the world.

Creating your server instance

You now need to create a server instance to deploy to:

appstax server create

Only the app owner can create its server instance. Other developers are allowed to start/stop, deploy code and view server status and logs.

You will be prompted to choose a .appstax.io subdomain for you app if you haven't previously done so. If you typed myapp, your servercode api will be available at http://myapp.appstax.io/api. You can verify that the server is up and running by opening that url now.

You can also check the server status on the command line:

appstax server status

Deploying to the server

Deploying your own "Hello World" app to the server is easy:

appstax deploy server

The contents of the server directory will be packaged and uploaded. Try changing some code in the server/app.js file then deploying again and reloading you browser to see the changes.

Writing server APIs with Express

In this example we're going to use the Express framework on Appstax ServerCode to write a simple REST API.

First need to install the express node module. Run this command from inside the server folder to install express in server/node_modules/express.

npm install express --save

Then replace the contents of app.js with the "Hello world" equivalent for Express:

var express = require("express");
var app = express();

app.get("/api", function (req, res) {
  res.send('Hello API from Express');
});

var server = app.listen(3000, function () {
  var port = server.address().port;
  console.log("Server running at port " + port);
});

Remember that you must have a file named app.js in your server directory. ServerCode will only look for this file when bootstrapping your application so without it nothing much will happen. You can of course load your own files and modules from within the app.js file.

###Adding a new end-point

Say we want to make an end-pont that just show the time and date on the server. In your app.js file insert the following code:

app.get("/api/time", function (req, res) {
  var datetime = new Date();
  res.send("The server time is: " + datetime.toTimeString());
});

Now run appstax deploy server again and visit http://<your subdomain>.appstax.io/api/time and you should see the time of the server in your browser.

Using Node.js modules

If you want to use npm packages that's OK. Just make sure your node_modules directory are up to date and the appstax command-line tool will copy all modules to the server.

Here's an example: we want to build a RSS feed reader using the Google Feed API using a custom feed component served from npm. Type the following in your terminal:

npm install google-feed-api --save

The feed Google feed component is now downloaded and placed in your node_modules directory, and when your run appstax deploy server that directory will be copied to the server.

Add the following code to your app.js file:

var gfeed = require("google-feed-api");

app.get("/api/feed.html", function (req, res) {
  var feed = new gfeed.Feed('http://rss.nytimes.com/services/xml/rss/nyt/World.xml'); 

  feed.load(function(feed){     
    var html = makeHTML(feed.feed.entries);     
    res.send(html);     
  });       
});


function makeHTML(feed) {    
  var html = "";

  for (var i = 0; i < feed.length; i++) { 
    html += "<h3><a href='" + feed[i].link + "'>";
    html += feed[i].title + "</a></h3>";
    html += "<p>" + feed[i].contentSnippet + "</p>";
  }
  return html;
}

The above code fetches the lates world news from the New York Times rss feed and augments it with html tags before returning it to the client for rendering. You can read more about the API here.

Run appstax deploy server again and visit /api/feed.html to see the HTML-formatted news.

Using the Appstax JavaScript SDK from the server

The Appstax JavaScript SDK is Node.js compatible and you can use it the same way as from a client. We're going to make some example code that logs some analytics data to the Appstax back-end.

First install the appstax-express npm package:

npm install appstax-express --save

Both the appstax and appstax-express npm packages can be used with Node.js, but appstax-express contains additional express middleware to handle user sessions and CORS requests.

Now import and init appstax in app.js by adding the two following lines. You need to replace your-app-key with your own app key. Run appstax info to view it or find it in the Admin UI.

var appstax = require("appstax-express");
appstax.init("your-app-key");

Then we need to create a new collection to hold our data. You can use the Appstax Admin UI or the command line as follows:

appstax collection stats ip:string time:string agent:string

This command will create a collection named stats with three string columns (ip, time, agent). Now, in app.js modify the feed end-point like this:

app.get("/api/feed.html", function (req, res) {
  var start = process.hrtime();

  var feed = new gfeed.Feed('http://rss.nytimes.com/services/xml/rss/nyt/World.xml'); 

  feed.load(function(feed){     
    var html = makeHTML(feed.feed.entries);     
    res.send(html);     
  });

  var end = process.hrtime(start);
  logToServer(req,res,end);
});

And implement the logging function like this in app.js:

function logToServer(req,res, time) {
  var stat = appstax.object("stats");

  stat.ip = req.headers['x-forwarded-for'] || 
    req.connection.remoteAddress || 
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;

  stat.time = time[1]/1000000 + "ms";
  stat.agent = req.get('User-Agent');
  stat.save();
}

Now, refresh the browser window visiting the /api/feed.html end-point to generate some log entries. When done, issue the following command in your terminal:

appstax find stats

This commands list all data in the stats collection.

Viewing the server log

The app.js examples above used console.log(msg) to write log messages. To see these messages run this command:

appstax server log 20

It prints the last 20 lines of the log that console.log writes to. You can return any number of lines by replacing 20 with the number you want.

Starting, stopping and viewing server status

To see if your server is running:

appstax server status

And to start or stop your server:

appstax server start
appstax server stop