|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Reflection; |
| 5 | +using System.Runtime.CompilerServices; |
| 6 | +using System.Text; |
| 7 | +using System.Threading.Tasks; |
| 8 | + |
| 9 | +namespace JSONAPI.Core |
| 10 | +{ |
| 11 | + public sealed class MetadataManager |
| 12 | + { |
| 13 | + #region Singleton pattern |
| 14 | + |
| 15 | + private static readonly MetadataManager instance = new MetadataManager(); |
| 16 | + |
| 17 | + private MetadataManager() { } |
| 18 | + |
| 19 | + public static MetadataManager Instance |
| 20 | + { |
| 21 | + get |
| 22 | + { |
| 23 | + return instance; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + #endregion |
| 28 | + |
| 29 | + private readonly ConditionalWeakTable<object, Dictionary<string, object>> cwt |
| 30 | + = new ConditionalWeakTable<object, Dictionary<string, object>>(); |
| 31 | + |
| 32 | + /* |
| 33 | + internal void SetDeserializationMetadata(object deserialized, Dictionary<string, object> meta) |
| 34 | + { |
| 35 | + cwt.Add(deserialized, meta); |
| 36 | + } |
| 37 | + */ |
| 38 | + |
| 39 | + internal void SetMetaForProperty(object deserialized, PropertyInfo prop, object value) |
| 40 | + { |
| 41 | + Dictionary<string, object> meta; |
| 42 | + if (!cwt.TryGetValue(deserialized, out meta)) |
| 43 | + { |
| 44 | + meta = new Dictionary<string, object>(); |
| 45 | + cwt.Add(deserialized, meta); |
| 46 | + } |
| 47 | + meta.Add(prop.Name, value); |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + internal Dictionary<String, object> DeserializationMetadata(object deserialized) |
| 52 | + { |
| 53 | + Dictionary<string, object> retval; |
| 54 | + if (cwt.TryGetValue(deserialized, out retval)) |
| 55 | + { |
| 56 | + return retval; |
| 57 | + } |
| 58 | + else |
| 59 | + { |
| 60 | + //TODO: Throw an exception here? If you asked for metadata for an object and it's not found, something has probably gone pretty badly wrong! |
| 61 | + return null; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Find whether or not a given property was |
| 67 | + /// posted in the original JSON--i.e. to determine whether an update operation should be |
| 68 | + /// performed, and/or if a default value should be used. |
| 69 | + /// </summary> |
| 70 | + /// <param name="deserialized">The object deserialized by JsonApiFormatter</param> |
| 71 | + /// <param name="prop">The property to check</param> |
| 72 | + /// <returns>Whether or not the property was found in the original JSON and set by the deserializer</returns> |
| 73 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 74 | + public bool PropertyWasPresent(object deserialized, PropertyInfo prop) |
| 75 | + { |
| 76 | + object throwaway; |
| 77 | + return this.DeserializationMetadata(deserialized).TryGetValue(prop.Name, out throwaway); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments