Skip to content

Instantly share code, notes, and snippets.

@JoachimL
Last active March 21, 2017 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoachimL/dffac22c265e018e5f62471ff35222bf to your computer and use it in GitHub Desktop.
Save JoachimL/dffac22c265e018e5f62471ff35222bf to your computer and use it in GitHub Desktop.
HTTP triggered function
#r "Newtonsoft.Json"
using System;
using System.Configuration;
using Newtonsoft.Json;
using System.Net;
// These are the (interesting parts) of the models returned from the kolonial API.
// The actual JSON returned contains more properties, but I see no reason to bother the deserializer
// with more than what we actually need.
public class KolonialSearchResponse {
public KolonialProduct[] Products {get;set;}
}
public class KolonialProduct {
public string Id {get;set;}
public string Barcode { get; set; }
public string Brand {get; set;}
public string Name {get; set;}
}
static HttpClient HttpClient = null;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
if(HttpClient == null)
HttpClient = CreateHttpClient(log);
string barcode = GetBarcodeFromRequest(req);
// Request product from kolonial
var httpResult = await HttpClient.GetAsync("https://kolonial.no/api/v1/search/?q=" + barcode);
if (!httpResult.IsSuccessStatusCode)
{
// not much we can do here, so just log the error and return an error status code.
log.Error($"Error occured when getting data from kolonial.");
return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Product not found");
}
else
{
var json = await httpResult.Content.ReadAsStringAsync();
if (json != null)
{
log.Info($"Processing JSON: {json}");
var results = JsonConvert.DeserializeObject<KolonialSearchResponse>(json);
// If the search call returns anything but a single product
// we have no idea how to handle it.
if(results.Products != null && results.Products.Length == 1)
{
var product = results.Products.First();
product.Barcode = barcode;
return req.CreateResponse(HttpStatusCode.OK, product);
}
}
return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found");
}
}
public static HttpClient CreateHttpClient(TraceWriter log)
{
log.Info("Instantiating HTTP client.");
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-Client-Token", ConfigurationManager.AppSettings["KolonialToken"]);
httpClient.DefaultRequestHeaders.Add("User-Agent", ConfigurationManager.AppSettings["KolonialUserAgent"]);
return httpClient;
}
public static string GetBarcodeFromRequest(HttpRequestMessage req){
return req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "barcode", true) == 0)
.Value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment