Archives

All posts for the month December, 2015

Project: API Web Server

I am currently building a simple Node.js based API web server. It’s primarily a proof-of-concept project that will be used when developing the API for another project. I have written similar servers for other projects in the past, this one should be cleaner and easier to use.

At the core of the server is the node http2 module. This provides the HTTP/2 web server, plus fall back to HTTP/1.1 support. HTTP/2 is the latest version of the hypertext transfer protocol and supports multiplexing data transfer connections, allowing multiple concurrent data streams. HTTP/1.1 serializes data transfer, meaning one stream has finish before another can begin. Below is the code that instantiates the http2 server

//Options for the http2 server
const httpServerOptions = {
        key: fs.readFileSync(path.join(__dirname, 'keypath/key.pem')),
        cert: fs.readFileSync(path.join(__dirname, 'keypath/cert.pem'))
};

var http2server;
if (process.env.HTTP2_PLAIN) {
    console.log('Setting up HTTP2 Plain');
    http2server = http2.raw.createServer({}, processRequest);
} else {
    console.log('Setting up HTTP2 TLS');
    http2server = http2.createServer(httpServerOptions, processRequest);
}

processRequest is the callback function that handles the server requests, it takes two objects as parameters, request and response.

function processRequest(request, response) {
//process the request and provide a response ...

Since this is a simple server, it does not need to support many options. My current server implementation supports the following requirements:

  • Passes GET and POST requests to the API endpoints
  • API endpoints as modules
  • Dynamically load modules during development
  • Transfers html, js, css, and txt, files with correct mime types
    • The allows it to be used as a basic file web server
  • Display 404 when file or endpoint cannot be loaded
  • Error logging

This is not a complete web server, but it could eventually be. A complete web server would support multiple HTTP response codes, have a plugin infrastructure, support large numbers of mime types, access logging, and numerous other features. At this point it is good for development and is easy to expand.

Since I have written similar servers in the past I looked at my previous code bases, it wasn’t pretty. I ended up finding duplicated code and signs of obvious confusion. When I coded the new server I made some similar mistakes, but upon reviewing the code I was able to move duplicated code into dedicated functions, then reworked the flow of the requests so that the main method was simpler. In the past I over complicated functions, stuffed too many actions into them. Simplify the methods increase the number of overall methods, but produced code that is easier to read and debug.

I added dedicated methods for displaying 404 messages, writing content and its mime type back to the requester, and wrote a method dedicated to handling POST and GET requests.

function processRequestMethod (request) {
  if (request.method === 'POST') {
    var data='';
    request.on('data', function(chunk) {
      data += chunk;
    });
    request.on('end', function() {
      return qs.parse(data);
    });
    request.on('error', function(e) {
      console.error('ERROR with POST request '+e.message);
    });
  } else {
  //Process as GET
    return qs.parse(url.parse(request.url).query);
  }
}

My Next goal was to dynamically load API modules, to be continued in part 2.

Fibro has completely changed my life, yet I still try to live my old limitless life. I was having a really good streak the other week and pushed myself until my body basically shut down Saturday afternoon. It has never been unusual for me to crash on a Saturday afternoon, but I used to be able to recover from those crashes. This latest one I partially recovered from the following day, but I overdid it again, leaving me out of commission for a couple of days.

Fatigue loves to come around a corner at full speed, crashing me when I least expect it. It starts off with me feeling tired, I start to feel slow, then I start to get cold. If I keep on pushing through it I will eventually end up chilled with heavy brain fog. It is the chill that usually forces me under the covers, even if I try to stay awake, I’ll usually pass out. Waking up is not pleasant, usually involves headaches and fog, but there is one good thing, I usually wake up warm. Napping helps me break chills, sometimes it is the only way I can warm up.

I have searched for alternative methods of staying warm. I’ll bundle myself up in blankets, gloves, cardigans and sweaters, but not everything always works. Spirits will only warm me when I’m not drinking to warm up. I’ve tried various alcohols, some work very well at helping with pain and sometimes they’ll warm me up, but it’s not worth the physical or mental damage drinking can do. Alcohol and fibro don’t always mix well, in some people they trigger flareups and hangovers are nightmareish.

My body temperature seems to be in a constant flux, some days I will stay warmer than others. There are times when setting my AC to 80 leaves me freezing under blankets, yet I’ll be outside in shorts and a tee in 72f weather. My bedroom temperature stays relatively static, but I will go to totally comfortable, wake up freezing or boiling, constantly throwing blankets on and off trying to find an equilibrium. Some days I will wake up nice warm with only one blanket on me, other days I’ll wake up freezing with all the blankets on me.

The constant flux in body temperature limits what I can comfortably enjoy. Restaurants often feel freezing cold to me, even the office I work in is too cold for me. The constant exposed to the cold causes my hands and fingers to become stiff, I have trouble typing or writing. It is not unusual for me to leave an air conditioned business shivering. It makes me not want to go out, makes me want to head immediately home. In the mornings it can actually be hard for me to motivate myself out of bed because I will get a chill in the few feet between my bed and bathroom. Changing into exercise clothes can leave me frigid, even if I’ll be sweating in the same temperature an hour later.

I’m trying to find the patterns, but they’re hard to identify. I am working on software that I believe will help me identify the patterns. I believe that finding the patterns are key to getting fibro under control. I have kept health and food diaries, inconsistent and paper based. It has allowed me to identify some health patterns, such as the fatigue/chill link and fibroflu and rain links. I’m certain there are more patterns, complex patterns that require excellent monitoring and pattern matching to identify.

I hypothesis that monitoring/recording the mix of activity (or lack thereof), diet, sleep, weather, and medication will reveal patterns which contribute to flareups. Over the past months I have been designing the software to accomplish this. I have recently began programming the backend, which will accumulate and process the data. Soon I will start work on the frontend user interface. I look forward to blogging more about this as I progress on the project.