class

USERcycle

Description

A Node.JS module, which provides an object oriented wrapper for the USERcycle v1 API.

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

class

Client

Description

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

Client can load any version of the [[usercycle]] client API, with the requirement that a valid routes.json definition file is present in the api/[VERSION] directory and that the routes found in this file are implemented as well.

Upon instantiation of the Client class, the routes.json file is loaded from the API version specified in the configuration and, parsed and from it the routes for HTTP requests are extracted. For each HTTP endpoint to the HTTP server, a method is generated which accepts a Javascript Object with parameters and an optional callback to be invoked when the API request returns from the server or when the parameters could not be validated.

When an HTTP endpoint is processed and a method is generated as described above, Client also sets up parameter validation with the rules as defined in the routes.json. A full example that illustrates how this works is shown below:

Example

First, we look at a listing of a sample routes.json routes definition file:

{
    "defines": {
        "constants": {
            "name": "USERcycle",
            "description": "A Node.JS module, which provides an object oriented wrapper for the USERcycle v1 API.",
            "protocol": "http",
            "host": "api.usercycle.com",
            "port": 80,
            "pathPrefix": "/api/v1",
            "dateFormat": "YYYY-MM-DD HH:MM:SS Z",
            "requestFormat": "query"
        },
        "response-headers": [
            "Date",
            "Content-Type"
        ],
        "params": {
            "uid": {
                "type": "String",
                "required": true,
                "validation": "",
                "invalidmsg": "",
                "description": "A unique user identifier typically the user ID in your internal database."
            },
            "id": {
                "type": "String",
                "required": true,
                "validation": "",
                "invalidmsg": "",
                "description": "unique object identifier returned after an object is posted"
            }
        }
    },

    "events": {
        "get": {
            "url": "/events/:id.json",
            "method": "GET",
            "params": {
                "$id": null
            }
        }
    }
}

You probably noticed that the definition is quite verbose and the decision for its design was made to be verbose whilst still allowing for basic variable definitions and substitions for request parameters.

There are two sections; 'defines' and 'events' in this example.

The defines section contains a list of constants that will be used by the Client to make requests to the right URL that hosts the API. The events section defines the endpoints for calls to the API server, for events specifically in this example, but the other API sections are defined in the exact same way. These definitions are parsed and methods are created that the client can call to make an HTTP request to the server. there is one endpoint defined: . In this example, the endpoint events/get will be exposed as a member on the Client object and may be invoked with

client.events.get({
    "uid": "bob"
}, function(err, ret) {
    // do something with the result here.
});

All the parameters as specified in the Object that is passed to the function as first argument, will be validated according to the rules in the params block of the route definition. Thus, in the case of the uid parameter, according to the definition in the params block, it's a variable that first needs to be looked up in the params block of the defines section (at the top of the JSON file). Params that start with a $ sign will be substituted with the param with the same name from the defines/params section. There we see that it is a required parameter (needs to hold a value). In other words, if the validation requirements are not met, an HTTP error is passed as first argument of the callback.

Implementation Notes: the method is NOT case sensitive, whereas url is. The url parameter also supports denoting parameters inside it as follows:

"get": {
    "url": "/events/:id.json",
    "method": "GET"
    ...
}
instance method

Client#authenticate

    • Client#authenticate(options)
      • null
    • options
      • Object
    • Object containing the authentication type and credentials

    • type
      • String
    • At the moment, USERcycle only supports 'token'

    • token
      • String
    • USERcycle API token

Set an authentication method to have access to protected resources.

Example
// basic
usercycle.authenticate({
    type: "token",
    token: "[your API key]"
});
instance method

Client#httpSend

    • Client#httpSend(msg, block, callback)
      • null
    • msg
      • Object
    • parameters to send as the request body

    • block
      • Object
    • parameter definition from the routes.json file that contains validation rules

    • callback
      • Function
    • function to be called when the request returns. If the the request returns with an error, the error is passed to the callback as its first argument (NodeJS-style).

Send an HTTP request to the server and pass the result to a callback.

instance method

Client#setupRoutes

    • Client#setupRoutes()
      • null

Configures the routes as defined in a routes.json file of an API version

setupRoutes is invoked by the constructor, takes the contents of the JSON document that contains the definitions of all the available API routes and iterates over them.

It first recurses through each definition block until it reaches an API endpoint. It knows that an endpoint is found when the url and param definitions are found as a direct member of a definition block. Then the availability of an implementation by the API is checked; if it's not present, this means that a portion of the API as defined in the routes.json file is not implemented properly, thus an exception is thrown. After this check, a method is attached to the Client instance and becomes available for use. Inside this method, the parameter validation and typecasting is done, according to the definition of the parameters in the params block, upon invocation.

This mechanism ensures that the handlers ALWAYS receive normalized data that is of the correct format and type. JSON parameters are parsed, Strings are trimmed, Numbers and Floats are casted and checked for NaN after that.

Note: Query escaping for usage with SQL products is something that can be implemented additionally by adding an additional parameter type.

mixin

cohorts

Description

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

instance method

cohorts#getDaily

    • cohorts#getDaily(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • date (String): Required. Return the last four sets of cohort metrics from the specified starting day. The starting date needs to be specified in the following format: YYYY-MM-DD. Validation rule: ^[0-9]{4,4}-(?:0|1)[0-9]{1,1}-[0-2]{1,1}[0-9]{1,1}$ .
  • count (Number): Optional. Specifies the number of results to try and retrieve, up to a maximum of 100. Validation rule: ^[0-9]+$ .
instance method

cohorts#getMonthly

    • cohorts#getMonthly(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • date (String): Required. Return the last four sets of cohort metrics from the specified starting day. The starting date needs to be specified in the following format: YYYY-MM-DD. Validation rule: ^[0-9]{4,4}-(?:0|1)[0-9]{1,1}-[0-2]{1,1}[0-9]{1,1}$ .
  • count (Number): Optional. Specifies the number of results to try and retrieve, up to a maximum of 100. Validation rule: ^[0-9]+$ .
instance method

cohorts#getWeekly

    • cohorts#getWeekly(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • date (String): Required. Return the last four sets of cohort metrics from the specified starting day. The starting date needs to be specified in the following format: YYYY-MM-DD. Validation rule: ^[0-9]{4,4}-(?:0|1)[0-9]{1,1}-[0-2]{1,1}[0-9]{1,1}$ .
  • count (Number): Optional. Specifies the number of results to try and retrieve, up to a maximum of 100. Validation rule: ^[0-9]+$ .
mixin

events

Description

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

Instance methods

instance method

events#create

    • events#create(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • uid (String): Required. A unique user identifier typically the user ID in your internal database.
  • action_name (String): Required. The name of the action performed by the user. Example values: signed_up, activated. Validation rule: ^(signed_up|activated|came_back|upgraded|downgraded|billed|referred|referred_by|canceled)$ .
  • properties (Hash): Optional. A list of properties associated with this action.
  • occurred_at (String): Optional. A UTC formatted timestamp when this event occurred, e.g. 2010-11-17 19:45:54 UTC
instance method

events#get

    • events#get(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • id (String): Required. unique object identifier returned after an object is posted
instance method

events#list

    • events#list(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • count (Number): Optional. Specifies the number of events to try and retrieve, up to a maximum of 100. Validation rule: ^[0-9]+$ .
  • page (Number): Optional. Specifies the page of results to receive. Validation rule: ^[0-9]+$ .
  • identity (String): Optional. Returns events for a specific user.
  • action (String): Optional. Returns events that match the specified action. Validation rule: ^(signed_up|activated|came_back|upgraded|downgraded|billed|referred|referred_by|canceled)$ .
  • since (String): Optional. Returns events that were recorded since the time specified. The results are ordered in decending order (newest to oldest). The since parameter should be in the yyyymmddhhmmss format and in UTC. Validation rule: ^[0-9]{4,4}(?:0|1)[0-9]{1,1}[0-3]{1,1}[0-9]{1,1}[0-2]{1,1}[0-9]{1,1}[0-6]{1,1}[0-9]{1,1}[0-6]{1,1}[0-9]{1,1}$ .
class

HttpError

Description

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

Instance methods

instance method

HttpError#toJSON

    • HttpError#toJSON()
      • Object

Returns a JSON object representation of the error.

instance method

HttpError#toString

    • HttpError#toString()
      • String

Returns the stringified version of the error (i.e. the message).

mixin

people

Description

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

Instance methods

instance method

people#list

    • people#list(msg, callback)
      • null
    • msg
      • Object
    • Object that contains the parameters and their values to be sent to the server.

    • callback
      • Function
    • function to call when the request is finished with an error as first argument and result data as second argument.

Params on the msg object:
  • identity (String): Optional. Searches for people whose identity matches the value.
  • count (Number): Optional. Specifies the number of results to try and retrieve, up to a maximum of 100. Validation rule: ^[0-9]+$ .
  • page (Number): Optional. Specifies the page of results to receive. Validation rule: ^[0-9]+$ .
class

Util

Description

Copyright 2012 Cloud9 IDE, Inc.

This product includes software developed by Cloud9 IDE, Inc (http://c9.io).

Author: Mike de Boer mike@c9.io

instance method

Util#escapeRegExp

    • Util#escapeRegExp(str)
      • String
    • str
      • String
    • string to escape

Escapes characters inside a string that will an error when it is used as part of a regex upon instantiation like in new RegExp("[0-9" + str + "]")

instance method

Util#extend

    • Util#extend(dest, src, noOverwrite)
      • Object
    • dest
      • Object
    • destination object

    • src
      • Object
    • source object

    • noOverwrite
      • Boolean
    • set to true to overwrite values in src

Shallow copy of properties from the src object to the dest object. If the noOverwrite argument is set to to true, the value of a property in src will not be overwritten if it already exists.

instance method

Util#isFalse

    • Util#isFalse(c)
      • Boolean
    • c
      • mixed
    • value the variable to check. Possible values: false The function returns true. 'false' The function returns true. 'off' The function returns true. 0 The function returns true. '0' The function returns true.

Determines whether a string is false in the html attribute sense.

instance method

Util#isTrue

    • Util#isTrue(c)
      • Boolean
    • c
      • mixed
    • value the variable to check. Possible values: true The function returns true. 'true' The function returns true. 'on' The function returns true. 1 The function returns true. '1' The function returns true.

Determines whether a string is true in the html attribute sense.

instance method

Util#log

    • Util#log(arg1[, arg2][, type])
      • null
    • arg1
      • mixed
    • messages to be printed to the standard output

    • type
      • String
    • type denotation of the message. Possible values: 'info', 'error', 'fatal', 'exit'. Optional, defaults to 'info'.

Unified logging to the console; arguments passed to this function will put logged to the standard output of the current process and properly formatted. Any non-String object will be inspected by the NodeJS util#inspect utility function. Messages will be prefixed with its type (with corresponding font color), like so:

[info] informational message
[error] error message
[fatal] fatal error message
[exit] program exit message (not an error)

The type of message can be defined by passing it to this function as the last/ final argument. If the type can not be found, this last/ final argument will be regarded as yet another message.

instance method

Util#toCamelCase

    • Util#toCamelCase(str[, upper])
      • String
    • str
      • String
    • string to transform

    • upper
      • Boolean
    • set to true to transform to CamelCase

Transform a string that contains spaces or dashes to camelCase. If upper is set to true, the string will be transformed to CamelCase.

Example:

Util.toCamelCase("why U no-work"); // returns 'whyUNoWork'
Util.toCamelCase("I U no-work", true); // returns 'WhyUNoWork'