autorest icon indicating copy to clipboard operation
autorest copied to clipboard

'Exists' operations in generated code

Open bitsforthought opened this issue 11 years ago • 6 comments

In the Search SDK, we end up writing a custom 'Exists' method for every resource that looks something like this (note that this example is not based on AutoRest-generated code yet):

internal partial class IndexOperations
{
    public async Task<bool> ExistsAsync(string indexName, CancellationToken cancellationToken)
    {
        try
        {
            // Get validates indexName.
            await GetAsync(indexName, cancellationToken);
            return true;
        }
        catch (CloudException e)
        {
            if (e.Response.StatusCode == HttpStatusCode.NotFound)
            {
                return false;
            }

            throw;
        }
    }
}

This seems generally useful for any REST client. There should be a way to tell AutoRest to generate this for a given 'Get' operation -- perhaps a custom x-ms property in the spec?

bitsforthought avatar Aug 06 '15 04:08 bitsforthought

Hmm... sometimes this is expressed with a HEAD request.

I'm not sure this should go in the swagger... Perhaps, this is just a convenience method created by the generator.

As an aside, if you receive a 404 on a GET, I think one should model the expected return and we send back a null. Then, the client can decide to handle it how they would like.

Thoughts?

devigned avatar Aug 06 '15 15:08 devigned

Good point about the HEAD request; that's a better way to implement it. If it's going to be a different verb, then maybe it can go in the Swagger spec?

As for null versus exception on 404, I'd recommend against returning nulls in general. Null is called the billion dollar mistake for good reason. :-)

Let's mull over the implications of using HEAD instead of GET, and I'll keep writing Exists myself until we figure out a better way.

bitsforthought avatar Aug 06 '15 16:08 bitsforthought

yeah... I'm pretty negative on using exceptions for control flow as well :).

devigned avatar Aug 06 '15 17:08 devigned

So am I, which is why I wrote Exists so my customers don't have to catch the exception or check for null. It's a great pattern.

bitsforthought avatar Aug 06 '15 17:08 bitsforthought

We actually already have a special logic for HEAD. If the verb is HEAD and status codes are 204 or 404 we automatically return boolean - true for 204 and false for 404.

stankovski avatar Aug 08 '15 00:08 stankovski

That is exactly what I'm looking for. Thanks Denis!

bitsforthought avatar Aug 10 '15 18:08 bitsforthought