@@ -0,0 +1,116 @@
/**
* @description URL dispatcher
*/
@RestResource(urlMapping = ' /*' )
global class RestDispatcher
{
// dispatchables
static Map <RequestType , List <Dispatchable >> dispatchables ;
// requestTypes
enum RequestType {HTTPGET , HTTPPOST , HTTPPUT , HTTPDELETE , HTTPPATCH }
// static constructor
static
{
dispatchables = new Map <RequestType , List <Dispatchable >>
{
RequestType .HTTPGET = > new List <Dispatchable >(),
RequestType .HTTPPOST = > new List <Dispatchable >(),
RequestType .HTTPPUT = > new List <Dispatchable >(),
RequestType .HTTPDELETE = > new List <Dispatchable >()
};
// register your class here
}
/**
* @description HTTP methods
*/
@HTTPGet
global static void doGET ()
{
execute (RequestType .HTTPGET );
}
@HTTPPOST
global static void doPOST ()
{
execute (RequestType .HTTPPOST );
}
@HTTPPATCH
global static void doPATCH ()
{
execute (RequestType .HTTPPATCH );
}
@HTTPPUT
global static void doPUT ()
{
execute (RequestType .HTTPPUT );
}
@HTTPDELETE
global static void doDELETE ()
{
execute (RequestType .HTTPDELETE );
}
private static boolean match (String requestURI , String dispachableURI )
{
List <String > dispachableURIList = dispachableURI .split (' /' );
List <String > requestURIList = requestURI .split (' /' );
if (dispachableURIList .size () != requestURIList .size ())
{
return false ;
}
else
{
for (Integer i = 0 ; i < dispachableURIList .size (); i ++ )
{
if (! dispachableURIList .get (i ).contains (' {' ) && dispachableURIList .get (i ) != requestURIList .get (i ))
{
return false ;
}
}
}
return true ;
}
private static Map <String , String > getParameters (String requestURI , String dispachableURI )
{
List <String > dispachableURIList = dispachableURI .split (' /' );
List <String > requestURIList = requestURI .split (' /' );
Map <String , String > result = new Map <String , String >();
for (Integer i = 0 ; i < dispachableURIList .size (); i ++ )
{
if (dispachableURIList .get (i ).contains (' {' ))
{
result .put (dispachableURIList .get (i ).subString (1 , dispachableURIList .get (i ).length ()), requestURIList .get (i ));
}
}
return result ;
}
private static void execute (RequestType requestType )
{
RestRequest request = RestContext .request ;
for (Dispatchable d : dispatchables .get (requestType ))
{
if (match (RestContext .request .requestURI , d .getURIMapping ()))
{
d .execute (getParameters (RestContext .request .requestURI , d .getURIMapping ()));
}
}
}
/**
* @description dispatchable
*/
global interface Dispatchable
{
String getURIMapping (); // e.g. /teams/{teamNumber}/members/{memberId}
void execute (Map <String , String > parameters );
}
}