Sunday, April 19, 2009

Need More Rest

Note: This is all brand new and to be considered experimental right now, but I thought I'd give you guys a heads-up:

ERXRest can do a lot of various things, but I was never happy with the API and the complexity of the interfaces you have to implement to use it. Anjo did some work with ERD2REST, which is cool, but I still have a bunch of cases where I just want something like what Rails offers -- a very easy way to map annotated URLs onto (direct) action methods. When you just want to quickly make a json interface to your app (especially CRUD interfaces), but with support for additional custom actions (which ERXRest doesn't address), the rails approach makes a lot of sense ... So here are some new API's to try to make that easier:

in your Application constructor:


ERXRouteRequestHandler routeRequestHandler = new ERXRouteRequestHandler();
routeRequestHandler.addDefaultRoutes(Reminder.ENTITY_NAME);
routeRequestHandler.addDefaultRoutes(Person.ENTITY_NAME);
ERXRouteRequestHandler.register(routeRequestHandler);

(you can also add custom routes -- i.e. "/people/{person:Person}/company/{company:Company}/{something:String}" -- but the one above defines all the default routes that rails supports ... check out the javadoc for ERXRestRequestHandler for more info).

then you can make a controller class:

public class PeopleController extends ERXRouteController {
public PeopleController(WORequest request) {
super(request);
}

public Person person() {
Person person = (Person) objects().objectForKey("person");
return person;
}

public ERXKeyFilter personFilter() {
ERXKeyFilter filter = ERXKeyFilter.filterWithAttributes();
filter.include(Person.PREFERENCE_GROUPS).includeAttributes();
return filter;
}

public WOActionResults createAction() throws Exception {
ERXKeyFilter personFilter = personFilter();
personFilter.include(Person.COMPANY);
Person person = (Person) create(Person.ENTITY_NAME, personFilter);
editingContext().saveChanges();
return response(personFilter(), person);
}

public WOActionResults updateAction() throws Exception {
Person person = person();
update(person, personFilter());
editingContext().saveChanges();
return response(personFilter(), person);
}

public WOActionResults showAction() {
Person person = person();
return response(personFilter(), person);
}

public WOActionResults indexAction() throws Exception {
NSArray people = Person.fetchPersons(editingContext(), null, Person.LAST_NAME.asc().then(Person.FIRST_NAME.asc()));
return response(personFilter(), editingContext(), Person.ENTITY_NAME, people);
}
}

This is basically a DirectAction class, but it has a bunch of tools to make it easy to do the rest creates, updates, and lookups ... there is no security by default (just like rails), so you have to enforce security however makes sense, but it handles xml, json, and plist requests and for the cases where you're just doing relatively straightforward things, this is way easier than the other ERXRest stuff, though you trade off some optimized fetching and automatic security filtering that ERXRest does in exchange for the simplicity.

The determination of what to include/exclude both in rendering and in parsing is done with ERXKeyFilters, which allow hierarchical definitions of include/exclude filters for keypaths (so you say things like: start with an "include all attributes" base, but exclude "password", then include the "tasks" relationship, but don't show any attributes for that (so you just get task ids)). The code for that would be:


ERXKeyFilter filter = ERXKeyFilter.filterWithAttributes();
filter.exclude(Person.PASSWORD);
filter.include(Person.TASKS);


As an example of actually hitting the API, btw:

curl -X PUT -d '{ lastName="SchragTestAlso"; preferenceGroups=( {id=1000012; name="SomeName2"; } ); }' http://vdoop.local:51915/cgi-bin/WebObjects/MDTask.woa/ra/person/1000008.plist

this updates the person with id 1000008 with plist format, sets the last name to "SchragTestAlso", and replaces their preference groups with a single existing preference group id 1000012 and also updates the name of that group to be "SomeName2".

curl -X PUT -d '{ lastName:"SchragTestAlso"; preferenceGroups:[ {id:1000012; name:"SomeName2"; } ]; }' http://vdoop.local:51915/cgi-bin/WebObjects/MDTask.woa/ra/person/1000008.json

is the same thing in JSON, and

curl -X PUT -d '<Person><lastName>SchragTestAlso</lastName><preferenceGroups><PreferenceGroup id="1000012"><name>SomeName2</name></PreferenceGroup></preferenceGroups></Person>' http://vdoop.local:51915/cgi-bin/WebObjects/MDTask.woa/ra/person/1000008.xml

is the same thing in XML ... notice that just by changing the extension it automagically does request and response filtering for you with the right parser/writer.

8 comments:

  1. Thanks Mike. This is indeed pretty nice stuff..I have played around with it and so far it has worked nicely. Though I am still trying to understand the entity delegates. Would it be possible to throw a bit more light on entity delegates ?

    Thanks

    ReplyDelete
  2. entity delegates is the old API and are no longer used at all with the new API

    ReplyDelete
  3. Hi Mike,
    I'm using ERXRest for a while now and is running beautifully for me. An issue i am encountering is "I want to add additional(custom or derived) methods/attributes to be returned as a part of response". For e.g in a Person entity, I have a method fullName which should be part of Person's view attributes.

    Any ideas/suggestions for the same.

    Thanks
    Thanks

    ReplyDelete
  4. if you're using entity delegates you would have to manually override the set of display keys -- i honestly don't know if you can do it or not. that stuff is deprecated as far as i'm concerned.

    if you're using the new route apis, you just add the key to your filter -- showFilter.include(new ERXKey("fullName"))

    ReplyDelete
  5. Thanks Mike. I am using route APIs only but still it was failing. (May be bcz I have a month old version of the ERXRest)

    It worked with a little change in the BeanInfoClassDescription class. I had to add a method "methodDescriptorKeys" to fetch the method names from the bean. Also had to change _addAttributesAndRelationshipsForObjectOfEntity method in the ERXRestRequestNode class to avoid throwing this exception if the method exists in the beanclass "This key filter specified that the key aKeyName should be included on nonModelClassDescription.entityName() but it does not exist."

    ReplyDelete
  6. Oh, are you using WO-style accessor methods that aren't getXxx? Yeah BeanInfo won't know about those. I thought about magically supporting them, but was afraid of exposing too many methods by accident. Can you submit your patch to the Wonder Jira?

    ReplyDelete
  7. nevermind .. trunk has support for this now.

    ReplyDelete
  8. Thanks :-). You were faster

    ReplyDelete