How to delay the response of my Web API - asp.net-web-api

I am working on a Web API project and that has an Artist Web API Controller. On there, there is the api/artist method that is a GET for all artists.
When making the call to this method, I would like a 3 second delay before I serve the data, how can I achieve this?
CODE
public class ArtistController : ApiController
{
private GlContext db = new GlContext();
// GET api/Artist
public IQueryable<Artist> GetArtists()
{
return db.Artists;
}
}
I know that you wouldn't want to do this in a production environment, but I am playing with preloaders, and in order to test them properly I need to introduce this delay.

If it is just for testing you can always go for Thread.Sleep(3000)
http://msdn.microsoft.com/en-us/library/d00bd51t%28v=vs.110%29.aspx

Related

Mocking a controller enters controller instead of mock

The bounty expires in 5 days. Answers to this question are eligible for a +50 reputation bounty.
Chris Rockwell wants to draw more attention to this question.
I am trying to get comfortable with tests in Laravel and playing around with Dusk.
Given I have the following controller:
class CoursesController extends Controller {
private ApiServiceProvider $api;
public function __construct(ApiServiceProvider $apiServiceProvider) {
$this->api = $apiServiceProvider;
}
public function getCoursesCache(array $cIds = []) : array {
// Breakpoint here - always gets hit when running tests
if (empty($cIds)) {
$cIds = Request::capture()->query('cIds');
$cIds = explode(',', $cIds);
}
return $this->api->getCoursesCache($cIds);
}
}
Which is used by a route:
Route::get('/api/v1/courses/cache', 'App\Http\Controllers\Api\CoursesController#getCoursesCache')->name('courses.cache');
This route is used internally by a VueJS component, which is ultimately what I'd like to test.
I am using Dusk to do some browser based testing and I want to mock the controller response for getCoursesCache. However, when I use the following (with a breakpoint in the controller method) I always enter the controller instead of just returning the mock.
$courseController = $this->mock(CoursesController::class)->makePartial();
$item = new CourseCacheItem();
$item->name = $course->name;
$courseController->shouldReceive('getCoursesCache')
->with([$course->getKey()])
->andReturn([$item]);
$this->browse(function (Browser $browser) use ($course) {
$browser->visit('/')
->waitFor('.course-card-container--data-loaded', 10)
->screenshot('filename')
->assertSee($course->name);
});
I've also tried this to create the mock:
$cc = $this->createMock(CoursesController::class);
$item = new CourseCacheItem();
$item->name = $course->name;
$cc->expects($this->once())->method('getCoursesCache')->with([$course->getKey()])->willReturn([$item]);
Edit: I've also now tried Mocking and Spying on the injected service ApiServiceProvider but the code enters that real class during the test run as well.
My expectation is that my breakpoint within the actual CoursesController would never be hit - what am I doing wrong?
Your issue here is that you are dealing with two separate Laravel Runtime.
You can check this issue for more infos.
Basically, when you are making a Dusk test with an Http call, Dusk will make a real Http call to a fresh Laravel instance/runtime (using Chrome Headless).
So you end up having one runtime where you are lunching the test, and the second one where dusk is making an http call.
The second Laravel instance is not running your Mock and doesnt know about it. That's why you end up in the actual Controller.
One solution i found in the past is making a route responsible to mock what i need.
This route should be called in the the html page before the assertion is happening.
So when you make a Dusk http call some Js (in the second Laravel instance) will call the route and the mock will be setup.
Fortunately for you there is great package that can handle this for you. https://github.com/NoelDeMartin/laravel-dusk-mocking

Web API - Handling the long running call when aggregating the calls

I have a web api project which works as a GateWay for other Mobile clients. When the mobile client makes a call to this Gateway it internally calls the existing services which are hosted by another project and it aggregates the results and return to the client. I have recently come across a situation when my gateway is internally making 3 calls first 2 are returning the data fast but the 3rd call is taking lot of time I want to know the best way to handle this scenario.
Ensure that the return type of API action methods is async Task<YourModelDataType>.
For example, let's say you have a HomeController controller as follows:
public class HomeController : ApiController
{
public async Task<YourModelDataType> Index()
{
return new YourModelDataType()
{
Property1 = await ApiService1.GetData(),
Property2 = await ApiService2.GetData(),
Property3 = await ApiService3.GetData(),
};
}
}
Ensure that calls to the other API projects are awaited. This improves scalability on the server side. i.e. server resources are free to serve other requests while awaiting response from other API services.

Update clients in asp.net core 2.0 using SignalR

I am going through several examples on Asp.net Core WebAPI with SignalR where most of them are demonstrating simple chat application where this is what Hub returns:
return Clients.All.InvokeAsync("Send", message);
And this is how it gets called in Startup.cs
routes.MapHub<Chat>("chat");
The above example is good if message is not be send and updated to all the clients. In my case I have several APIs to be called whenever a data is changed:
Like Bank Transaction is done, I have to update ledger and several other reports at client side. But I don't see any option to pass Json.
Not finding exactly how to do this so that WebAPI gets refreshed everytime a change is there in the database.
As far as I understood, here "chat" is the endpoint which will be called from the frontend.
In this case what will happen to the endpoint I have created so far. Have a look at the below code example:
This api is to be called every time an entry is done:
public async Task<object> GetMarket(string marketshortcode)
{
Markets market = new Markets(marketshortcode);
return market.GetMarket();
}
and this the entry:
[Authorize]
[HttpPost]
public async Task<object> sellCurUser([FromBody] SellCur model)
{
if (model != null)
{
SellCurUser suser = new SellCurUser();
suser.sellcur = model;
my addition code...
}
return ....
}
There are several more endpoints which needs to be called at certain update/creation.
Now the point is how these apis will be changed or even not changed at all.
Do anyone have any example to understand it simply.

Web API 2 - Unity IOC - Shared instance per request variable

I am using web api with unity IOC.
web api client passes client-id in request header and based on this value dependencies are resolved to create a external dll's method instance.
creation of this instance take around 6-7 seconds which is creating performance issues in web api.
What I want is to prevent instance creation for call with same client-id in header.
This is how I have implemented till now:-
//========================== ArchiveFactory ==========================
ArchiveFactory archiverFactory = (HttpRequest httpRequest) =>
{
container.RegisterType<IArchive, Archive>("Archive",
new HierarchicalLifetimeManager(),
new InjectionConstructor(
new ResolvedParameter<IStoreClient>(),
Helper.GetArchiveContext(httpRequest))
);
return container.Resolve<IArchive>("Archive");
};
container.RegisterInstance(archiverFactory);
To be specific in my requirement - I am calling amazon services to retrieve images and there is a corporate dll which invokes amazon.
You can use caching mechanism at the controller/API layer(e.g Strathweb.CacheOutput.WebApi2) and you can decorate the controller method like this below. It's can cache based on parameter so if request comes in with same parameter, it will return results from cache.
[HttpGet]
[Route("")]
[CacheOutput(ServerTimeSpan = 60, ExcludeQueryStringFromCacheKey = true)]
public IHttpActionResult GetProducts(string clientId)
{
var product = new List<Product>();
return Ok(product);
}
Also, you might want to check the class constructor that you are trying to instantiate for issues that is taking it too slow. You may want to consider using lazy loading too if that will apply.

What is a good web service for ajax interactions? in Zend Framework context?

When you are designing a page that will use javascript and ajax to interact with your server, what is the best technology you should use?
What I mean by using is basically things like sending and receiving data for simple CRUD, and things like autocompletion and search.
I usually write my own server, I read the $_POST variable, and I use Jquery's jQuery.post() to send stuff to the server and also read stuff.
I was wondering if I should use a more standard protocol such as:
XML_RPC
REST
SOAP
JSON_RPC
Please tell me if I should be using any of these or something else, and also justify your response as to what protocol/technology is more suited for these kind of things.
I tend to use REST/JSON because it's easiest and fastest in most cases. I hate XML parsing and Zend Framework supports creating a REST application very easily. On top of that, it would allow you to separate your view and data layers to different servers if you really needed to scale. I often have 'regular' controllers and REST controllers in the same modules, it's pretty easy to get the hang of.
The get/post/put/delete actions correspond to the HTTP request type
class MyRestController extends Zend_Rest_Controller
{
public function init()
{
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
}
public function getAction()
{
}
public function postAction()
{
}
public function putAction()
{
}
public function deleteAction()
{
}
}
And then you have to initialize the route in your bootstrap:
protected function _initRestRoute()
{
$this->bootstrap('frontController');
$frontController = Zend_Controller_Front::getInstance();
$restRoute = new Zend_Rest_Route($frontController);
$frontController->getRouter()->addRoute('default', $restRoute);
}
Some light reading:
http://www.techchorus.net/create-restful-applications-using-zend-framework
http://www.xfront.com/REST-Web-Services.html
http://www.develop.com/httpstatuscodesrest

Resources