Introduction to Code Services

Each code service receives a req object and a resp object

req object

function myService(req, resp){

	log(req)
	// Below is the value of req
	{
		// The email of the user that invokes this code service
		"userEmail": "rreinold@clearblade.com",
		// Any parameters passed into this service
		// You can also pass in parameter using Test Parameters
		// in the Developer Console in browser
		"params": {
		  "key1":"value1",
		  "key2":"value2"
		}
		// System Key of this system
		"systemKey": "e095a19d0b94e48dee9bff87e5fd01",
		// System Secret of this system
		"systemSecret": "E095A19D0B9ACD9EFA86AEEDFCC001",
		// The active user token used to invoke this service
		"userToken": "U1hNf7o4bEXpiE4aGhb-79MQv4jH0v2U8nH5Oq_anGEjQh5kfAozv6CbDhDHA4xPwlRSkh2XeD1KhdQg6Q==",
		// is logging enabled (see [log](/Log.js) library)
		"isLogging": true,
		// User UUID of user who invoked this service
		"userid": "fc8cfcea0a96ebebc7f5d4edd414",
	}
}

resp Object

When you make a call with the resp object, the code service completes, and ends its lifecycle.

Failing to complete your service

Your code service will call resp.success() by default if you fail to call resp.success or resp.error

To complete a code service, one of the two methods must be called:

resp.success()

Success: true

When you use this method, a “success”: true key will be included to your response.

Example 1: We return a success message string

function myService(req, resp){
	var message = "Successfully updated position!"
	resp.success(message) // Code Service terminates
}

Example 2: We return a JSON Object with our success

function myService(req, resp){
	var winning = {
		message:"We succeeded!",
		context:"We tried it with the included query",
		query: {
			first_name:"Julian"
		}
	}
	resp.success(winning) // Code Service terminates
	}
}

Success: false

When you use this method, a “success”:false will be included to your response

Example 1: An error message is returned

function myService(req, resp){
	var errorMessage = "Unable to process due to missing data!"
	resp.error(errorMessage) // Code Service terminates
}

Example 2: An error JSON object is returned

function myService(req, resp){
	var error = {
		message: "Unable to process due to missing data!",
		query: {
			first_name:"Harry",
			last_name:"Potter"
		}
	}
	resp.error(error) // Code Service terminates
}

Throwing errors

If your code service throws an uncaught error, the code service defaults to the aforementioned behavior for unterminated code service: resp.success() is called by default)