I’ve a server application with Vapor 3, I set up three models Book, Author, Publisher, relative routers and controllers with CRUD and relationships (both Author and Publisher have a Sibling relationship with book).
All would be fine was not for the incoming data: the Json I receive has a different data structure, where the publishers and authors are stored in arrays inside the book.
I cannot decode on Book.self because I would lose the data relevant to publishers and authors, so I created BookTotal, which has no representation on the database (no migration) so I could
req.content.decode(BookTotal.self).flatMap
At this point I would like to call the save or update functions on the Publisher and Author controllers passing the BookTotal.Publisher and BookTotal.Author array.
But, while I can reach the methods either with something like
`PublisherController.Save()`
Or
let client = req.make(Client.self)
let response = client(“path/for/the/router”)
I don’t know how to pass them the data. The CRUD methods inside the controllers have Request as parameter but I don’t know how to build one.
let newReq = Request()
newReq.content = BookTotal.Author
Would be my guess, but Request wants a Container and I don’t know how I should go about that.
I searched around but couldn't find any example/tutorial on such issue.
Am I even on the right path with this?
So you have a couple of options to achieve what you want to do. One option is to rewrite your request handlers in your controllers to accept that data using one of the helper functions. So
func savePublisher(_ req: Request, data: Publisher) throws -> Future<Publisher>
You can then change router.post("your", "url", use: savePublisher) to router.post(Publisher.self, at: "your", "url", use: savePublisher). Then if your code you can call that method and pass the data through as needed.
A (potentially) better way would be to extract the code that saves a publisher out into a separate function which you can then call from your savePublisher route and your bookTotal route. For basic routes this is likely to be the same as the first option, but for most complex routes this is the way to go.
Related
I am developing a rest api on .Net core 2.2 following MVC pattern.
I have a controller with a post method like this...
// POST: api/Todo
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(string param, [FromBody] TodoItem item)
{
// some work...
return CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item);
}
And it works fine.
The customer asked to have an api on the same route, but the Json body could have 2 different structures, bearing the same data on different schemas.
I considered using
PostTodoItem(string param, [FromBody] Object item)
{
// TryCast item to one of the possible POCO classes then work with the correct one.
}
Do you know a better way, maybe with some advanced routing and filtering option?
This is not really possible nor desirable. Pretty much the core tenant of REST is a URI uniquely represents a particular resource. If you've got a URI like POST /todo, then the post body should be a "todo" and it should create a new "todo" based on that. Here, that is a TodoItem, so that is all that should ever be posted.
REST aside, this just won't work. When your action is activated, the modelbinder attempts to bind the post body to the param(s) that the action accepts. It basically just news up whatever type the param is, and then attempts to find something from the post body to bind to the various properties on that type. This is an intentionally simplistic description of what's happening; the important part is that the type of the param informs how the post body is bound. If you bind to an object (which has no members) or even a base type, then the only members of the post body that will be bound are those that are present on that type, not derived types thereof. Anything that cannot be bound is discarded.
Long and short, you need a unique route for each type of thing you're working with. Under the hood, you can share or otherwise reuse code by factoring out common functionality into private methods, employing inheritance, etc., but you need a distinct action and route to handle each case.
What do I want:
I want to be able to generate swagger documentation that passes a key/value into the URL. This so that I can use generic arguments controller to handle my requests like Dictionary.
If swagger can't generate it, is there a way to generate the documentation by using reflection on my objects? This so that I can still use generic methods
If not, what would be the best way to let everyone know what the correct approach would be.
Why do I want it
I'm developing a new API and I'm using swagger to create the documentation. In this API I want to work with some generic methods to prevent hardcoding things. For example on the PATCH method I use a Dictionary<string, string> to get the property/value combination and in the GET I use a custom object as the argument. In both cases, swagger can't generate the correct parameter fields, because it takes the argument as url key.
Example action & form - incorrect
public async Task<IActionResult> Patch(int id, Dictionary<string, string> viewModel)
{
return await ConnectionWrapper(() => connector.Patch(id, viewModel));
}
This uses the body, not the query
Other examples - incorrect
In the GET I have a model with a custom modelbinder to handle all the rest URL arguments. The problem is because the model is defined it sees the filter as a property.
Then it is in the URL, but it will look like http://example.com/controller/method/id?sort=prop_asc&filter=propTwo%3D=value, instead of http://example.com/controller/method/id?sort=prop_asc&propTwo=value
Desired output
I've modified the HTML to simulate what I would like in the picture above. The URL that would be called would be http://example.com/controller/method/id?propertyName=propertyValue.
I don't mind if there would be only one option to add a generic key/value pair because with it I can demonstrate what I want.
Expected solution
I think the solution lies in the MapType startup method of swagger or in an implementation of the IOperationFilter, but I haven't been able to figure it out.
In Spring (java) and in .NET also, you can add an object in request scope?
i.e. a user makes a request, you perform some look in a filter or base controller, and then you can add this object into the request object for this current request only
Now in your Action you can check if the key exists and use this object in your action method.
In Play 2 Requests are immutable so you would generally wrap them and pass them around rather than modifying them.
You'd usually use something called action composition to do what you want. Action composition lets you write common code for actions so that you can pre-process a requests and maybe pass the action some data from the request.
Check out the Authenticated example in the docs which provides the action with an AuthenticatedRequest object. The AuthenticatedRequest object wraps the existing Request (rather than modifying it) and adds an additional username value.
As Rich said, you can use Action Composition and, if you want to put more information in Request context, you can use Http.current().args.put("key","value").
Does anyone have or know of an example which demonstrates loading data via a GWT RPC call into a ListStore using Sencha GXT 3.0? I know there are numerous examples of using the ModelData and BeanModel interfaces used in the 2.x versions but 3.0 does away with the need to use these interfaces and supposedly allows for POJO objects to be loaded in using classes which implement the ValueProperty interface.
I have seen the RequestFactoryBinding example and the RequestFactory Grid example in the 3.0 Explorer but those appear to demonstrate the use of a custom Data Proxy and a Receiver. I assume from reviewing the code in those examples that these techniques/classes may be required but that is not made apparent anywhere. It's possible that there is more documentation forthcoming but so far I haven't been able to find much of anything beyond that javadocs and the Explorer which lacks some of the source classes used in the example methods.
Links to both examples below.
The RequestFactoryBinding Example:
http://www.sencha.com/examples/#ExamplePlace:requestfactorybinding
RequestFactory Grid example:
http://www.sencha.com/examples/#ExamplePlace:requestfactorygrid
DataProxy and Loader are used mostly to facilitate a) relying on the server for filtering/paging/sorting, or b) reuse between parts of the application for getting access to the same pieces of data. They are not required (as in 2.x) in cases where the client only loads data once, or where manual store management is done.
The various store loading classes (ListStoreBinding, LoadResultListStoreBinding) demonstrate internally how the ListStore can be fed items. This first way allows you to replace the existing items in the store from the onSuccess method in your RPC callback or RequestFactory receiver:
List<MyData> newItems = ...;//response from server
ListStore<MyData> store = ...;//current store to replace/update
store.replaceAll(newItems);
If only loading once, or only appending, not replacing, the other method should be used:
store.addAll(newItems);
Items can be added one by one using store.add, however this will result in an event per item, and should be avoided.
Edit: Also, and this may not totally be clear coming from 2.x, but no superclass/interface is required for data itself. ValueProvider is only used as an external abstraction for how models are manipulated - how values are generically read or set from any kind of model. The PropertyAccess interface allows ValueProvider (and other) instances to be generated by just the property name that the values will be get/set from using bean accessors. ValueProvider types/instances are not required for loading data, merely for the data widgets themselves to extract the data they are displaying, and to make modifications after the user edits the values.
Knowing these pieces, the loader/proxy mechanism will be loading data in the same basic way. The Loader is responsible for being told what settings (paging, filtering, and/or sorting) to use when loading, then triggering the load - different subclasses have different responsibilities, accept different load config types, and return different results. The DataProxy then is the mechanism that actually talks to whatever holds the data, asynchronously if on a server, and informs the loader when the results are available via a callback.
The examples listed in the question both use RequestFactory, but there are several examples as well that use RPC, and a few loading from just JSON or XML. In http://www.sencha.com/examples/#ExamplePlace:paginggrid the main data loading parts are as follows:
// The rpc async instance
final ExampleServiceAsync service = GWT.create(ExampleService.class);
// As in Ext GWT 2, there is a convenience proxy for RPC to just pass the callback
// directly to the RPC call. If you need a custom callback, just be sure to invoke
// `callback.onSuccess` with the final result.
RpcProxy<PagingLoadConfig, PagingLoadResult<Post>> proxy = new RpcProxy<PagingLoadConfig, PagingLoadResult<Post>>() {
#Override
public void load(PagingLoadConfig loadConfig, AsyncCallback<PagingLoadResult<Post>> callback) {
service.getPosts(loadConfig, callback);
}
};
// ...
// The loader itself has a reference to the proxy so that loader.load() results
// in a round trip to the server, as outlined above.
final PagingLoader<PagingLoadConfig, PagingLoadResult<Post>> loader = new PagingLoader<PagingLoadConfig, PagingLoadResult<Post>>(
proxy);
loader.setRemoteSort(true);
// This last piece - instead of 2.x where the loader is a parameter to the store,
// in 3 you directly wire the results of the loader to add the items into the
// store, as discussed in the first half of this answer
loader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, Post, PagingLoadResult<Post>>(store));
FWIW I spiked a GWTP Dispatch version of a remotely paged and sorted grid. Which is GWT RPC with a command pattern twist.
Assuming you're familiar with grids, you'll require an instance of:
RpcProxy
PagingLoader
LoadResultListStoreBinding
And the methods that need to be invoked:
PagingLoader.setRemoteSort(true)
PagingLoader.addLoadHandler()
Grid.setLoader()
PagingToolBar.bind()
I am trying to figure out the best way to design something. I am writing an iPhone App and for the most part I am using async calls to a web service. This means that I cam setting up a URLConnection, calling start and letting it call me back when the data is available or an exception occurs. This works well and I think is the correct way to handle things.
For example:
I request a list of people from a web service. The resulting list is Xml Person elements which will be translated into an objective-c "Person" object by my XmlDelegate.
When I call the function to get the person, I pass in a "PersonResultDelegate", which is a protocol with a single function called "PersonReceived:(Person *)p". So, each time I get a complete Person object, I call that method and all is well. So, my detail view (or search result view) just receives the elements as they are available.
The problem comes when I need to obtain more then one specific object. In my specific case, I need to get the first and last appointment for a person. So, I need to make two API calls to obtain these two single Appointment objects. Each Appointment object will result in a call to the registered AppointmentResultDelegate, but how will I know which is the first and which is the last? I also need to somehow handle the case when there is no "first" or "last" Appointments and the Delegate will never get called.
What would be the correct way design wise to handle this? Should I add some additional context information to the initial request which is passed back to the handle in the delegate? An opaque piece of data which only makes sense to the person who made the initial call? What are my other options?
Solution
What I actually ended up doing is just passing an opaque piece of data along with the Appointment to the delegate. So, when I request an appointment object I have a method like:
getNextAppointment withDelegate:self withContext:#"next"
getPrevAppointment withDelegate:self withContext:#"prev"
This way when the delegate gets called I know what appointment is being delivered.
"Each Appointment object will result in a call to the registered AppointmentResultDelegate, but how will I know which is the first and which is the last?"
By looking at the order in which you receive these callbacks. Or by looking at some value in that xml data. Like a sequence or data. I don't know your data of course.