RestKit Relationship Mapping by ID in URL

2019-07-03 18:42发布

问题:

Assume I have an API at users/1/items that returns a list of items for the user with an ID of 1.

Assume the API response is as follows:

{
    "items": [
        {
            "id": "1",
            "description": "Some item"
        }
    ]
}

Note that the response does not contain a user_id for relationship mapping. Is it possible in RestKit 0.20 to map to the user_id in the URL (in this case, 1)? If so, how? I could not find any mention of this in the docs/wiki.

回答1:

It is. You need to use the RKRouter class (which you would usually use with RKObjectManager). Once you're using routing and path patterns, you can use routing metadata in your mapping definitions.

RKRouter docs

Routing configuration example

How to use the meta data (section 'Metadata Mapping')

Additional metadata info



回答2:

You would actually accomplish this using what RestKit calls Relationship Routes.

Here is a short example:

RKRoute *aRoute = [RKRoute routeWithRelationshipName:@"user-items-relationship"
                              objectClass:User.class
                              pathPattern:@"users/:userid/items"
                                   method:RKRequestMethodGET];

Then you would get the items like this:

[[RKObjectManager sharedManager] getObjectsAtPathForRelationship:@"user-items-relationship"
                                                        ofObject:someUser
                                                      parameters:nil
                                                         success:^(RKObjectRequestOperation *operation, RKMappingResult *result)
 {
     NSLog("I win");
 }
                                                         failure:^(RKObjectRequestOperation *operation, NSError *error)
 {
     NSLog("I lose");         
 }];