Skip to content

Instantly share code, notes, and snippets.

@cdeckert
Created August 26, 2014 17:24
Show Gist options
  • Save cdeckert/6991034790b0a4c9a34c to your computer and use it in GitHub Desktop.
Save cdeckert/6991034790b0a4c9a34c to your computer and use it in GitHub Desktop.
Rest Dispatcher
/**
* @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);
}
}
@lfernandoavalos
Copy link

Thanks! This is awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment