mirror of https://github.com/Hax-io/libpb
- `fromJSON()` now throws `RemoteFieldMissing` exception if the input JSON does not have a field found in the input struct type `RecordType`
- Added a unittest to test the above
This commit is contained in:
parent
3d9b9a4976
commit
707a1b9373
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -61,3 +61,12 @@ public final class PocketBaseParsingException : PBException
|
|||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
public final class RemoteFieldMissing : PBException
|
||||
{
|
||||
this()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue