Home

vanevery edited this page Dec 12, 2014 · 16 revisions

Some Initial Documentation

Simple Request - Serve any file

serveFiles("dirname");

Typically you'll create a folder inside the main app folder, "public" or something of that sort which will contain any files that should get served. Any subdirectories will be accessed via the normal server path conventions:

 server.js
 public
      |
      index.html
      scripts
           |
           javascript.js
      css
           |
           styles.css
      images
           |
           index.png

Then use: serveFiles("public");

URLs would then be:

 http://server_ip:port/index.html
 http://server_ip:port/scripts/p5.js
 http://server_ip:port/css/styles.css
 http://server_ip:port/images/fancy.png

or relative URLs

 /index.html
 /scripts/p5.js
 /css/styles.css
 /images/fancy.png

Simple Request - Handle Programmatically

function run(request) {
    request.respond("Hello World");
}

Simple Request - Define handler - path

route('/handle',myHandler);
function myHandler(request) {
    // Do something
        request.respond("Something has been done");
}

Respond with JSON

request.header("application/json");
request.respond(JSON.stringify(data));

request Object

Contains all kinds of goodies

var util = require('util');
console.log(util.inspect(request));

Serve a static file

route("/index", serveIndex);

function serveIndex(request) {
  request.serveFile("public/index.html");
}

Query String

request.params.[name of param]

Form Handling - POST requests

request.fields.[name of field]

Routes with variables (RESTian routes)

route(/smething/:id/:otherthing, dosomething);

function dosomething(request) {
        var id = request.params.id;
        var otherthing = request.params.otherthing;
}

Database Save Data

var names = useDatabase("namesdb");
names.add({name: request.params.name});

Database Save Data with Callback

var names = useDatabase("namesdb");
names.add({name: request.params.name}, function(dbEntry) {
        console.log("New Entry ID: " + dbEntry._id);
});

Do redirect after

request.redirect("/somewhere");`

Database Get Data

var names = useDatabase("namesdb");
names.getAll(callback);

function callback(something) {
        namestext = "";
        for (i =0; i < something.length; i++) {
            namestext += something[i].name + " ";
        }
        request.respond("Hi all the peoples and " + namestext );
}

You can limit the query to a certain number of results by including that number in the query. This would return 100 results at most:

names.getAll(callback,100);

You can sort the query results by using an object containing the attribute you want to sort on with a 1 or -1 to indicate ascending or descending order.

Assuming the database contains objects such as this

[{"timestamp":1412886065906,"data":"420","_id":"w98zLstrdb0O9LUQ"},{"timestamp":1412886065910,"data":"418","_id":"Qq78mF9MY67Q9uyR"},{"timestamp":1412886065914,"data":"418","_id":"QBLYrX2EPtGKOHbE"},{"timestamp":1412886065919,"data":"417","_id":"7BVAhQxAAWy88cRq"},{"timestamp":1412886065927,"data":"417","_id":"9mZyIkoMftOqytXN"}]

You can sort the results like this, returning the last 100 results

names.getAll(callback,100,{timestamp: -1});

Search in Database

var db = useDatabase("something");

/* Database contains:
{name: "Marce", other: "some data"}
{name: "Other Person", other: "blah data"}
*/

// Search for "Marce" in "name" field:
var key = "name";
var value = "Marce";
db.search(key, value, gotIt);

function gotIt(data) {
    console.log("Got " + data[0].other);
}

One result from database using _id

var commentsdb = useDatabase("comments");

/* Database contains
{"name":"shawn","comment":"blah","_id":"1gtQqUVl1OIStGBn"}
{"name":"Joe","comment":"Miami","_id":"27xy64WKuuHv13AF"}
{"name":"shawn","comment":"hello","_id":"5EtqSRexBcVb3UAI"}
{"name":"Frank","comment":"Brooklyn","_id":"MGtvZP9zMmHnZWi0"}
*/

var someId = "1gtQqUVl1OIStGBn";
commentsdb.getOne(someId, gotIt);
function gotIt(data) {
    console.log("Got " + data.comment);
}

Templates

You can render the data retrieved into an HTML file for display as well. By default, Servi uses the EJS template rendering system which is a way that you can actually write JavaScript code to bind data within HTML:

// Create or use the existing database
var infoDB = useDatabase("namescities");

route('/viewdata',viewData);

function viewData(request) 
{
    infoDB.getAll(gotData);    

    function gotData(theData) {
        // Give the data from the database a name that we can access in our template
        var toRender = {cityData: theData};
        //  Render it
        request.render("template.html",toRender);
    }
}
<html>
  <head>
    <title>Names and Cities</title>
  </head>
  <body>
    <h1>Names and Cities</h1>

      <% for (i = 0; i < cityData.length; i++) { %>
        <%= cityData[i].name %> lives in <%= cityData[i].city %><br />
    <% } %>

  </body>
</html>     

As you can see, the HTML contains JavaScript code to access the data we are passing in. This code is surrounded by <% and %> symbols. We use <= variable %> to print or output data.