Created
February 27, 2015 02:06
-
-
Save jeffrymorris/77ea2eac7b9d2c07fb51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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