Skip to content

Commit

Permalink
add a test case for JSON.stringify() with wrapped class (issue #88)
Browse files Browse the repository at this point in the history
According to the [`JSON.stringify()` documentation][1] it's possible to add a
function `toJSON()` to prototype for custom conversion to JSON.

Added a `Xbase::to_json()` functions and exposed it as `toJSON()` into v8,
so that `JSON.stringify()` call for such objects would invoke the conversion
function.

Updated `create_X()` factory function to set the `X::var` on construction at
JavaScript side.

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior
  • Loading branch information
pmed committed Sep 22, 2018
1 parent 6e6b519 commit 5774dd0
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions test/test_class.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//
#include "v8pp/class.hpp"
#include "v8pp/module.hpp"
#include "v8pp/object.hpp"
#include "v8pp/property.hpp"

#include "test.hpp"
Expand All @@ -27,16 +28,30 @@ struct Xbase
int fun3(int x) volatile { return var + x; }
int fun4(int x) const volatile { return var + x; }
static int static_fun(int x) { return x; }

v8::Local<v8::Value> to_json(v8::Isolate* isolate, v8::Local<v8::Value> key) const
{
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Object> result = v8::Object::New(isolate);
v8pp::set_const(isolate, result, "key", key);
v8pp::set_const(isolate, result, "var", var);
return scope.Escape(result);
}
};

struct X : Xbase
{
};

template<typename Traits, typename X_ptr = typename v8pp::class_<X, Traits>::object_pointer_type>
static X_ptr create_X(v8::FunctionCallbackInfo<v8::Value> const&)
static X_ptr create_X(v8::FunctionCallbackInfo<v8::Value> const& args)
{
return X_ptr(new X);
X_ptr x(new X);
if (args.Length() > 0)
{
x->var = v8pp::from_v8<int>(args.GetIsolate(), args[0]);
}
return x;
}

struct Y : X
Expand Down Expand Up @@ -124,6 +139,7 @@ void test_class_()
.set("static_fun", &X::static_fun)
.set("static_lambda", [](int x) { return x + 3; })
.set("extern_fun", extern_fun<Traits>)
.set("toJSON", &X::to_json)
;

v8pp::class_<Y, Traits> Y_class(isolate);
Expand Down Expand Up @@ -165,6 +181,11 @@ void test_class_()
check_eq("X::extern_fun(5)", run_script<int>(context, "x = new X(); x.extern_fun(5)"), 6);
check_eq("X::extern_fun(6)", run_script<int>(context, "X.extern_fun(6)"), 6);

check_eq("JSON.stringify(X)",
run_script<std::string>(context, "JSON.stringify({'obj': new X(10), 'arr': [new X(11), new X(12)] })"),
R"({"obj":{"key":"obj","var":10},"arr":[{"key":"0","var":11},{"key":"1","var":12}]})"
);

check_eq("Y object", run_script<int>(context, "y = new Y(-100); y.konst + y.var"), -1);

auto y1 = v8pp::factory<Y, Traits>::create(isolate, -1);
Expand Down

0 comments on commit 5774dd0

Please sign in to comment.