Compare commits

...

2 Commits

3 changed files with 141 additions and 67 deletions

1
.gitignore vendored
View File

@ -14,3 +14,4 @@ libpb-test-*
*.o
*.obj
*.lst
liblibpb.a

View File

@ -1,11 +1,28 @@
module libpb.deserialization;
import std.json;
import libpb.exceptions : RemoteFieldMissing;
/**
* T
*
* Params:
* RecordType = type of the struct to construct
*/
mixin template T(RecordType)
{
import std.traits : FieldTypeTuple, FieldNameTuple;
/**
* Deserializes the provided JSON into a struct of type RecordType
*
* Params:
* jsonIn = the JSON to deserialize
* Throws:
* RemoteFieldMissing = if the field names in the provided RecordType
* cannot be found within the prpvided JSONValue `jsonIn`.
* Returns: an instance of RecordType
*/
public RecordType fromJSON(JSONValue jsonIn)
{
RecordType record;
@ -24,6 +41,12 @@ mixin template T(RecordType)
// pragma(msg, structValues[cnt]);
}
pragma(msg, "Bruh type");
pragma(msg, structTypes[cnt]);
// pragma(msg, __traits(identifier, mixin(structTypes[cnt])));
try
{
static if(__traits(isSame, mixin(structTypes[cnt]), byte))
{
mixin("record."~structNames[cnt]) = cast(byte)jsonIn[structNames[cnt]].integer();
@ -103,6 +126,11 @@ mixin template T(RecordType)
}
}
}
catch(JSONException e)
{
throw new RemoteFieldMissing();
}
}
return record;
}
@ -147,3 +175,39 @@ unittest
assert(person.obj["bruh"].integer() == 1);
//TODO: list test case
}
unittest
{
import std.string : cmp;
import std.stdio : writeln;
struct Person
{
public string firstname, lastname;
public int age;
public bool isMale;
public JSONValue obj;
public int[] list;
}
JSONValue json = parseJSON(`{
"firstname" : "Tristan",
"lastname": "Kildaire",
"age": 23,
"obj" : {"bruh":1},
"list": [1,2,3]
}
`);
mixin T!(Person);
try
{
Person person = fromJSON(json);
assert(false);
}
catch(RemoteFieldMissing)
{
assert(true);
}
}

View File

@ -61,3 +61,12 @@ public final class PocketBaseParsingException : PBException
{
}
public final class RemoteFieldMissing : PBException
{
this()
{
}
}