Skip to content

Instantly share code, notes, and snippets.

@jeffrymorris
Created February 27, 2015 02:06
Show Gist options
  • Save jeffrymorris/77ea2eac7b9d2c07fb51 to your computer and use it in GitHub Desktop.
Save jeffrymorris/77ea2eac7b9d2c07fb51 to your computer and use it in GitHub Desktop.
public static IDocumentResult<T> ExtractKeyAndInsert<T>(this IBucket bucket, string json, string fieldNameForId, out string id)
{
var type = typeof (T);
var document = type == typeof (object) ?
GetDocumentForDynamic<T>(json, fieldNameForId, out id) :
GetDocumentForPOCO<T>(type, json, fieldNameForId, out id);
return bucket.Insert(document);
}
static IDocument<T> GetDocumentForDynamic<T>(string json, string fieldNameForId, out string id)
{
var jObject = JsonConvert.DeserializeObject<JObject>(json);
Document<T> document;
JToken value = null;
if (jObject.TryGetValue(fieldNameForId, out value))
{
jObject.Remove(fieldNameForId);
document = new Document<T>
{
Id = id = value.ToString(),
Content = JsonConvert.DeserializeObject<T>(jObject.ToString())
};
}
else
{
throw new ArgumentException("Cannot find id field in json.", fieldNameForId);
}
return document;
}
private static IDocument<T> GetDocumentForPOCO<T>(Type type, string json, string fieldNameForId, out string id)
{
var document = new Document<T>
{
Content = JsonConvert.DeserializeObject<T>(json)
};
var idProperty = type.GetProperty(fieldNameForId);
if (idProperty == null)
{
throw new ArgumentException("Cannot find id field in json.", fieldNameForId);
}
id = idProperty.GetValue(document.Content).ToString();
document.Id = id;
return document;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment