How to recursively load nested objects identified by foreign-key in RestKit? - restkit

I have a bit of a unique problem. I've been reading RestKit docs for days and I'm pretty sure RK can do it, I'm just not sure how to set things up. When I first login my API returns a Contacts JSON that looks like below and I need to load the Group and Team that are referenced but NOT nested. If at all possible, I really need those loads to happen before the CoreData context gets saved.
Is it possible to configure RestKit to recurse these references automatically? If not, any suggestions on a good general approach?
{
"contactid": "003i0000016aiI8AAI",
"signed_waiver": "1",
"current_groupid": "T1Gj6mxcoXposmVUAA",
"current_teamid": "T1Gj6mxcoXposmVU11",
"createdby": "003i000001M4Y6fAAF",
"created": "Fri, 16 Jan 2015 21:14:07 +0000",
"updatedby": "003i0000016aiI8AAI",
"updated": "Sat, 13 Jun 2015 15:13:35 +0000"
}
If the waiver, current_groupid, or current_teamid is not set I need to display an on boarding wizard, if they then I proceed directly into the app which then requires loading details about the group and team (name, geometry, members, etc.). I can't change the server API to nest this structure directly.
I've been able to get my CoreData entity Contact to map and save. I struggled mightily with the current_groupid relationship and finally got it to not crash when I found 1787 and followed its advice. However, it's still getting saved as nil so I'm still doing something wrong...
let mapping = RKEntityMapping(forEntityForName: "Contact", inManagedObjectStore: rkManagedObjectStore)
mapping.identificationAttributes = ["apiID"]
mapping.addAttributeMappingsFromDictionary([
"contactid": "apiID",
"signed_waiver": "signedWaiver",
"current_groupid": "rkCurrentGroupId",
])
mapping.addConnectionForRelationship("currentGroup", connectedBy: ["rkCurrentGroupId": "apiID"])
For clarity, my Contact entity has String attributes for all of the above and a relationship for currentGroup that connects to Group.currentCanvassers.

No, it can't do it. RestKit doesn't automatically trigger any downloads, that's up to your code. RestKit takes your request and encodes it, then handles the response to decode it, performing mapping as required in both cases.
You could trigger automatic downloads in your code handling the completion or, more messily, in some of the other callbacks, but you can't make the save wait for them to complete.

Related

Best practice for custom REST actions with API Platform

This top-ranking Stackoverflow answer from 10 years ago suggests using POST /users/:user_id/reset_password to initiate a password reset.
I know the API platform recommends against using custom operations. The docs page for the Symfony Messenger integration uses a ResetPasswordRequest entity (with a username field). That makes sense to me. 
Say I have a User and Notification entity and maybe a joined UserNotification (with a hasRead) entity as well. I want to expose an endpoint on my API to mark all the notifications older than a month as read. So I might make a ClearOldNotification entity, again with a username field.
Another example might be I want a report showing Customers that haven't been contacted due to some criteria. So I want to join the tables in the server and return a custom JSON data object. Again I could make a CustomerNoContact entity.
The issue I see is that I now have a distinction between pure entities, like a User or Product, as opposed to these service type entities.
Is this method of making individual entities classes for actions the recommended, best practice for Symfony and API Platform?
Should I be name-spacing (or something) these entities differently within my app to distinguish them?
I could imagine on a really large and complex application you could have hundreds of these service entities, compared to the pure entities. Is that expected or desired?
Can anyone recommend some good resources on this pattern?
You're asking for a best practice for two different use cases. Let's break it down:
ClearOldNotification
I think you've already found the solution: using Messenger. As you've read, there is an example in the documentation for this use case:
#[ApiResource(collectionOperations: [
"post", "get", "delete",
"reset_password" => ["status" => 202, "messenger" => "input", "input" => ResetPasswordRequest::class, "output" => false, "method" => "POST", "path" => "/users/reset_password"]
]
)]
final class User
{
}
The ResetPasswordRequest class is a Data Transfer Object (DTO). In your ResetPasswordRequestHandler you should inject the service that is responsible for resetting the password and sending an email.
CustomerNoContact
This could be a Custom (Doctrine ORM) Filter.

Google Calendar API stopped returning events

Since today I have problem with one of 2 similar calls to Google Calendar API v3:
calendar.events.list
Both calls are requesting list of assignemnts and use privateExtendedProperty to filter them, but key=Value pairs are different.
When I have privateExtendedProperty set to myStatus=READY it returns events I need,
but when I set privateExtendedProperty to myId=agxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYkcHA3wgM
it returns no events, though I'm sure there are several events with this myId...
It appears that the calendar API list is returning an empty list when querying by a privateExtendedProperty with 90 characters long.
Everything worked fine for years, but it suddenly broke for some of my users this morning...
This is my request:
GET googleapis.com/calendar/v3/calendars/****/events?privateExtendedProperty=myId%3Dagxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYwauk6QgM&key={YOUR_API_KEY}
This is the result I see in API explorer:
{
"kind": "calendar#events",
"etag": "\"*****\"",
"summary": "*****",
"description": "*****",
"updated": "2018-02-20T03:18:35.098Z",
"timeZone": "Asia/Tokyo",
"accessRole": "owner",
"defaultReminders": [
],
"nextSyncToken": "CJDv1KDEs9kCEJDv1KDEs9kCGAU=",
"items": [
]
}
Update 1:
My privateExtendedProperty looks like this:
{
"myStatus": "READY",
"myId": "agxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYkcHA3wgM",
"another": "Another value",
"another2": "Another value2"
}
When I query events with "myStatus=READY" - event is returned, but when I do the same with "myId=agxzfm1..." - it returns emtpy list.
Update 2:
For those who have the same issue. As per suggestion, I created a new calendar and then duplicated some test data and tried long value in privateExtendedProperty query and it returned event as expected. It means, if this is a bug - not all calendars are affected and moving things to a new calendar might be a way to go.
The document for Extended Properties says the limitations as follows.
The maximum size of a property's key is 44 characters, and properties with longer keys will be silently dropped.
The maximum size of a property's value is 1024 characters, and properties with longer values will be silently truncated.
An event can have up to 300 shared properties totaling up to 32kB in size (keys size + value size).
An event can have up to 300 private properties, totaling up to 32kB in size (keys size + value size), across all "copies" of the event.
From this, it seems that your case is out of the above limitations. In my environment, also I tried your situation. As the result, it was found that myId=agxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYkcHA3wgM can be used.
So can you confirm the following points again?
It seems that your result retrieved by API explorer doesn't included extendedProperties in the property of items. When you set extendedProperties, it can be seen. If you use fields, it might be not able to be seen.
Can you set extendedProperties with myId=agxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYkcHA3wgM again?
You can set it using calendar.events.patch.
When you retrieve events with myId=agxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYkcHA3wgM using calendar.events.list, if you use the URL encoded value of myId%3dagxzfm1haWxmb29nYWVyNQsSDE9yZ2FuaXphdGlvbiIVYWN0aXZlZ2FtaW5nbWVkaWEuY29tDAsSBENhc2UYkcHA3wgM, please try to use the value without URL encode.
If this was not useful for you and I misunderstand your question, I'm sorry.
Edit :
If you retrieve the event using calendar.events.get, can the extendedProperties you set be seen? If you cannot see it, please insert extendedProperties again.
The endpoint is GET https://www.googleapis.com/calendar/v3/calendars/### calendar Id ###/events/### event Id ###?fields=extendedProperties%2Fprivate
In my environment, the same endpoint of yours works fine. So as a test, can you try to create new calendar and run that query? Because I worried whether the recent update of calendar affects this situation.

Allow multiple provider states with parameters ( Golang )

As our team ( namely myself and two other developers ) spiked on PACT past week or so, one of the areas of concern is not having the ability associate parameters to provider states. The absence of this key feature ( which is slated for version 3 release ), we likely will not get buy in from each of our respective service sub-teams.
#MattFellows - Any projections on when version 3 might be available for Go? Any chance we can get this feature earlier?
Allow multiple provider states with parameters
In previous versions, provider states are defined as a descriptive string. There is no way to infer the data required for the state without encoding the values into the description.
{
"providerState": "an alligator with the given name Mary exists and the user Fred is logged in"
}
The change would be:
{
"providerStates": [
{
"name": "an alligator with the given name exists",
"params": {"name" : "Mary"}
}, {
"name": "the user is logged in",
"params" : { "username" : "Fred"}
}
]
}
You are correct in that it won't be available until version 3.
You can still achieve what you are after, however. The state itself is just a handle for the Consumer to some set of data on the Provider - that can be a one-to-one or one-to-many mapping - it's completely up to you.
Typically the Provider is notified of the state during verification, it will then setup a test data fixture (often seeding a database) that sets up the 'state' of the entire system based on that reference, which allows the Consumer test to run.
Whilst the ability to pass through parameters and multiple states is nice, it's somewhat an advanced feature and I very much doubt this will be the first problem you run into as a team. I've never needed to use them myself.
For a crude but effective example of this, take a look at the gin code in the examples folder of the project.

New Feature - Update Responses

We have an internal database ID for each course we have. When using the batch function to create courses, the returned information doesn’t not give us any way to get this ID back so we cannot update our database and let it know that the course has been created.
Also updating the deletion response for the same reason would also be handy.
The response for a batch of deletes looks like:
--batch_123456
{}
--batch_123456
--batch_123456
{}
--batch_123456
--batch_123456
{}
--batch_123456
If they are all successful then it's not really a problem, but if something goes wrong then it's impossible to tell which ones were deleted and which ones were not deleted, because according to the API:
" The server may perform your calls in any order. Don't count on their being executed in the order in which you specified them."
A simple message that said "course #123 has been deleted" would be very helpful. That way I could program the callback code to update the database using the ID
For the course creation the response looks like:
--batch_123456
{
"id": "208571459",
"name": "***",
"section": "***",
"ownerId": "123456",
"creationTime": "2015-09-14T13:13:59.622Z",
"updateTime": "2015-09-14T13:14:02.820Z",
"enrollmentCode": "***",
"courseState": "PROVISIONED",
"alternateLink": "***"
}
--batch_123456
I only put in one response to save space. The ID is the new GoogleID of the course, the ID we actually send in which corresponds to the records in our DB does not get returned. So we have to use a combination of other data (ownerID + name) to get the record and update it, but this is not ideal and may not work fro everyone. Again adding in all of the information that get's sent into the response would be very helpful so we can use the callback properly.
I also want to add the more useful specific information should also be added to all error messages. In fact every batch response should have some sort of ID, that way the callback functions can be more useful.
As mentioned briefly in the documentation, you can pass an alias into Courses.id when creating a course to assign an alias to a course as you create it. The alias can include your internal identifier for the course and can be used in future requests.
Alternatively, each request in a batch can be assigned a unique Content-ID header, which will be returned in the response. Many client libraries provide built-in support for setting and getting these IDs.

Adviced on how to array a mongodb document

I am building an API using Codeigniter and MongoDB.
I got some questions about how to "model" the mongoDB.
A user should have basic data like name and user should also be able to
follow other users. Like it is now each user document keeps track of all people
that is following him and all that he is following. This is done by using arrays
of user _ids.
Like this:
"following": [323424,2323123,2312312],
"followers": [355656,5656565,5656234234,23424243,234246456],
"fullname": "James Bond"
Is this a good way? Perhaps the user document should only contain ids of peoples that the user is following and not who is following him? I can imaging that keeping potentially thousands of ids (for followers) in an array will make the document to big?
All input is welcome!
The max-document size is currently limited to 16MB (v1.8.x and up), this is pretty big. But i still think, that it would be ok in this case to move the follower-relations to an own collection -- you never know how big your project gets.
However: i would recommend using database references for storing the follower-relations: it's way easier to resolve the user from a database reference. Have a look at:
http://www.mongodb.org/display/DOCS/Database+References

Resources