1 module discord.w.json;
2 
3 string stripLastUnderscore(string s) @safe
4 {
5 	if (s.length && s[$ - 1] == '_')
6 		return s[0 .. $ - 1];
7 	else
8 		return s;
9 }
10 
11 mixin template OptionalSerializer(T)
12 {
13 	import std.traits;
14 
15 	import vibe.data.json;
16 	import vibe.data.serialization;
17 
18 	Json toJson() const @safe
19 	{
20 		Json ret = Json.emptyObject;
21 		static foreach (field; FieldNameTuple!T)
22 		{
23 			static if (hasUDA!(__traits(getMember, this, field), OptionalAttribute!DefaultPolicy))
24 			{
25 				if (__traits(getMember, this, field) != typeof(__traits(getMember, this, field)).init)
26 				{
27 					ret[field.stripLastUnderscore] = serializeToJson(__traits(getMember, this, field));
28 				}
29 			}
30 			else
31 				ret[field.stripLastUnderscore] = serializeToJson(__traits(getMember, this, field));
32 		}
33 		return ret;
34 	}
35 
36 	static T fromJson(Json src) @safe
37 	{
38 		T ret;
39 		Members: foreach (key, member; src.get!(Json[string]))
40 		{
41 			static foreach (field; FieldNameTuple!T)
42 			{
43 				if (field.stripLastUnderscore == key)
44 				{
45 					if (member.type != Json.Type.null_)
46 						__traits(getMember, ret, field) = deserializeJson!(typeof(__traits(getMember,
47 								ret, field)))(member);
48 					continue Members;
49 				}
50 			}
51 		}
52 		return ret;
53 	}
54 }