Hop.Method Class
Class used to define methods
Constructor
Hop.Method
()
Item Index
Methods
- addPostCall
- addPreCall
- authed
- cache
- cacheId
- cacheInvalidate
- defaultValues
- demand
- demandFile
- demands
- depricated
- emit
- emitAfter
- emitBefore
- findMethod static
- getMethod
- getPath
- inputModel
- inputModel
- longPoll
- model
- noCache
- optional
- optionalFile
- optionals
- requireRole
- requiresUser
- returnsBoolean
- returnsNumber
- returnsString
- returnsString
- secure
- sendCSRFToken
- usage
Methods
addPostCall
-
call -
phase
Add a function that will be called after this call is completed
Parameters:
-
callFunctionfunction to be called when this call is completed, which is passed the following parameters:
-
requestObjectthe ExpressJS / HTTP request object
-
inputObjectthe input parameters to the call
-
errthe resulting err from the call
-
resultObject- the result of the call
-
nextFunction- to be called when the callback is completed, causing the next call back to be called
-
-
phaseStringthe phase in which this function will be called (see below)
Phases
1. (Pre call phases) 2. **CALL** 3. first - called before any other phases 4. data - data processing and conversion 5. event - event emission 6. cache - cache phase 7. last - called last
Example:
api.get("load","/user/:userID").addPostCall(function(req,input,err,result,next){
//Let's caclulate the users age:
if(result && result.birthdate){
result.age = User.calculateAge(result.birthdate);
}
next();
},"data");
addPreCall
-
call -
phase
Add a function that will be called before this call is executed
Parameters:
-
callFunctionfunction to be called prior to when this call is executed , which is passed the following parameters:
-
requestObjectthe ExpressJS / HTTP request object
-
inputObjectthe input parameters to the call
-
onCompleteFunctionto be called if the function wants to short circuit and return a result
-
nextFunctionto be called when the callback is completed, causing the next call back to be called
-
-
phaseStringthe phase in which this function will be called (see below)
Phases
1. first - called first 2. demand - verifies that the required parameters are in place 3. conversion - will convert the input types to the expected types 4. validation - input validation 5. auth - authentication phase 6. event - event emission 7. cache - cache phase 8. last - the last set of calls to be called prior to the function call 9. **CALL** 10. (post calls)
Example:
api.get("load","/user/:userID").addPreCall(function(req,input,err,onComplete,next){
//If we have a user allow this call to complete
if(req && req.session && req.session.user){
next();
//If not return an error
} else {
return onComplete("Permission denied");
}
},"auth");
authed
()
chainable
Note that this method can only be called when there is a user in the session
This will only allow this method to be called if req.session.user exists
Example:
Hop.defineClass("UserService",UserService,function(api){
//Only allow this method to be called if a user is in the session
api.post("sendMsg","/user/:userId/message").authed();
});
cache
-
cacheFunc
Specifies a cache lambda for this call.
This funciton is used to specify a cache lambda which will determine how the result is cached.
Parameters:
-
cacheFuncFunction-
whenFunctionUsed to indicate when this cache function was evaluated, valid values are "before" and "after"
-
cacheFunctionThe cache object, which is used to return an action
-
idFunctionreturn the result of this function to specify the result should be cached -
id.idStringThe cache id -
id.durationNumberThe duration in seconds to cache the result for -
invalidateFunctionreturn the result of this function to specify the result should be invalidated -
invalidate.idStringThe cache id
-
-
reqObjectthe Express/HTTP request object
-
inputObjectthe input parameters for the call
-
errorObjectthe error as a result of calling this function (only valid after the call)
-
resultObjectthe result of this function (only valid after the call)
-
Example:
Hop.defineClass("Comment",new Comment(),function(api){
//This will cause the list to always attempt to hit the cache
api.get("list","/comment").cacheId("/comment/list/:start/:size").demand("start").demand("size").defaults({start:0, size:25});
api.del("delete","/comment/:commentId").cacheInvalidate("/comment/:commentId").demand("commentId");
api.get("load","/comment/:commentId").cache(function(when,cache,req,input,err,result){
if(Hop.hasUser(req)){
var userId = Hop.User.id(req);
//If we have a user, and that user is the one who posted the comment don't show a cached copy
if(userId == input.userId){
return false;
}
} else return cache.id("/comment/:commentId",60*5);
}).demand("commentId");
api.post("update","/comment/:commentId").cacheInvalidate("/comment/:commentId").demand("commentId");
});
cacheId
-
cacheId -
duration -
attempt
Specifies a cache Id to use for storing the result of this call.
This funciton is used to specify a cache id for the result causing the result to be associated with the id.
The specified cache ID will attempt to substitude variables in the id with those from the input, or from the user.
Parameters:
-
cacheIdStringthe id for the cached item
-
durationNumberthat the number of seconds result will be cached for
-
attemptForceto force the client side to cache the result for the specified duration, this will essentially mean the client side will not request the item again until expiration
cacheInvalidate
-
cacheId
Specifies a cache Id to invalidate.
This function is used to delete an item from the cache, so for example on an HTTP DEL command it may be desirable to delete an associated cache object.
The specified cache ID will attempt to substitude variables in the id with those from the input, or from the user.
Parameters:
-
cacheIdStringthe id for the cached item
defaultValues
-
defaults
Specify the default values for this call
These values will be copied into the input if no existing value is found.
Parameters:
-
defaultsObject
demand
-
name -
desc
Demand a parameter for a call
Parameters:
-
nameStringof parameter
-
descStringdescription of parameter
Example:
api.post("create","/user/profile/").demand("email","Email address");
demandFile
()
chainable
Demand a file be provided for this method.
Example:
api.post("create","/user/profile/").demandFile("avatar","Users avatar image");
demands
-
name
Specify a number of demands for for a call
Parameters:
-
nameStringname of parameter (+)
Example:
api.post("create","/user/profile/").demands("email","name","password");
depricated
()
chainable
Indicate that this method call has been depricated
emit
()
chainable
Alias to emitAFter
emitAfter
-
channel -
onEmit
Emit an event after calling this method
- The channel will have variables provided by the input parameters substituted into it.
Parameters:
-
channelStringThe channel to emit the event on
-
onEmitFunctionThe function which determines what is emitted
-
reqObjectThe Express/HTTP request object
-
inputObjectThe input object
-
errObjectThe error resulting from calling the method
-
resultObjectThe result of calling the method
-
Example:
api.post("processFile","/process/").emitAfter("/user/:userId",function(req,input,err,result){
//Emit an event to the specified channel
this.emit({err: err, result:result});
}).demand("userId");
emitBefore
-
channel -
onEmit
Emit an event prior to calling this method
- The channel will have variables provided by the input parameters substituted into it.
Parameters:
-
channelStringThe channel to emit the event on
-
onEmitFunctionThe function which determines what is emitted
-
reqObjectThe Exbeforess/HTTP request object
-
inputObjectThe input object
-
Example:
api.post("send","/message/send").emitBefore("/user/:to",function(req,input){
//Emit an event to the specified channel
this.emit({msg: input.msg, from: input.from});
}).demand("msg").demand("from").demand("to");
findMethod
()
String
static
Find a method by name
Returns:
Example:
Hop.defineClass("UserService",function(api){
api.get("load","/user/:userID")
});
var method = Hop.Method.findMethod("UserService.load");
Hop.log(method.getMethod()); //returns UserService.load
getMethod
()
String
Get the name of the method
This will get the name of the method
Returns:
Example:
Hop.defineClass("UserService",function(api){
api.get("load","/user/:userID")
});
var method = Hop.Method.findMethod("UserService.load");
Hop.log(method.getMethod()); //returns UserService.load
getPath
()
String
Get the full url for the method
This will get the full path for the url for the method.
Returns:
inputModel
-
model -
What
Use a model for the output
Parameters:
-
modelStringName of the model that is returned
-
WhatClassthe model is returned as (Array is the only valid value)
Example:
//Returns an array of vehicles
api.get("list","/vehicles").outputModel("Vehicle",Array);
inputModel
-
model -
What
Use a model for the input
Parameters:
-
modelStringName of the model that is used as an input
-
WhatClassthe model is inputted as (Array is the only valid value)
longPoll
()
chainable
Indicate this function performs longPolling
Example:
api.get("status","/server/:serverID/status").longPoll();
model
-
inputObject -
[outputModel]
Use a model for both input and output
Models are used to provide meta data for both UI and api generation
Parameters:
-
inputObjectObjectInput model
-
[outputModel]Object optionalOutput model
- Models require a field called _name which specifies the name of the model
- Models can have the following fields on types:
- type - The class name of the type, valid values are ( String, Number, Array, Object, Date, Boolean )
- subtype - A subtype for the field "ID", "Float", "JSON", "IDRef", "Tags"
- regex - A regex used to validate the fields
- regexMsg - A message which is displayed when the regex is not matched
- title - A title for the field, for UI purposes
- desc - A description of the field for UI purposes
- values - An array or object which contains possible values for this field
Example:
Hop.defineModel("User",function(model){
model.field("name").string().regex(/[A-Za-z]{3,10}/,"Usernames must be between 3 - 10 characters long and can only contain A-Z and a-z");
model.field("id").integer().ID();
model.field("email").string().title("Email");
});
Hop.defineClass("User",new User(),function(api){
api.post("create","/user").useModel("User");
api.get("list","/user").inputModel(SearchModel).outputModel(UserModel);
});
noCache
()
chainable
Indicate this function should avoid caching
Example:
api.post("create","/user/profile/").noCache();
optional
-
name -
desc
Optional parameter for a call
Parameters:
-
nameStringof parameter
-
descStringdescription of parameter
Example:
api.post("create","/user/profile/").optional("phoneNumber","Phone Number");
optionalFile
()
chainable
Specify that a file may optionally be provided as an input to this call.
Example:
api.post("create","/user/profile/").optionalFile("avatar","Users avatar image");
optionals
-
name
Specify a number of optionals for for a call
Parameters:
-
nameStringof parameter (+)
Example:
api.post("create","/user/profile/").optionals("email","name","password");
requireRole
()
Indicates that a user is required to call this function.
Example:
Hop.defineClass("UserService",function(api){
//This will cause this function to return "Permission denied" unless a user is found via Hop.User.hasRole();
api.get("view","/admin/user/:userID").requireRole("admin");
});
requiresUser
()
Indicates that a user is required to call this function.
Example:
Hop.defineClass("AccountService",function(api){
//This will cause this function to return "Permission denied" unless a user is found via Hop.User.exists();
api.get("/account/:accountID").requireUser();
});
returnsBoolean
()
chainable
This call returns a boolean value
returnsNumber
()
chainable
This call returns a number value
returnsString
()
chainable
This call returns a string value
returnsString
()
chainable
This call returns a file
secure
()
chainable
Note that this method can only be called using https
sendCSRFToken
()
chainable
Include the express CSRF token in the response headers for this method
The CSRF token is utilized to prevent cross site request forgery attacks, and is a middleware component for express.
See here for information: http://www.senchalabs.org/connect/middleware-csrf.html
By default HopJS will attempt to utilize the CSRF functionality in express if it is enabled, but some clients require a means to access the CSRF token, hence this function will will send the csrf token in the headers as 'x-crsf-token'
The primary usage for this function is with secure login functions
Example:
Hop.defineClass("UserService",UserService,function(api){
api.post("login","/login").demands("username","password").sendCSRFToken();
});
usage
-
usage
Describe this method
Parameters:
-
usageStringtext describing the function for documentation purposes
