From 5774dd0ae69738dc11f82ee754c7e61321231c77 Mon Sep 17 00:00:00 2001 From: Pavel Medvedev Date: Sat, 22 Sep 2018 18:05:49 +0200 Subject: [PATCH] add a test case for `JSON.stringify()` with wrapped class (issue #88) 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 --- test/test_class.cpp | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/test/test_class.cpp b/test/test_class.cpp index bf600083..f69d9e81 100644 --- a/test/test_class.cpp +++ b/test/test_class.cpp @@ -8,6 +8,7 @@ // #include "v8pp/class.hpp" #include "v8pp/module.hpp" +#include "v8pp/object.hpp" #include "v8pp/property.hpp" #include "test.hpp" @@ -27,6 +28,15 @@ 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 to_json(v8::Isolate* isolate, v8::Local key) const + { + v8::EscapableHandleScope scope(isolate); + v8::Local 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 @@ -34,9 +44,14 @@ struct X : Xbase }; template::object_pointer_type> -static X_ptr create_X(v8::FunctionCallbackInfo const&) +static X_ptr create_X(v8::FunctionCallbackInfo const& args) { - return X_ptr(new X); + X_ptr x(new X); + if (args.Length() > 0) + { + x->var = v8pp::from_v8(args.GetIsolate(), args[0]); + } + return x; } struct Y : X @@ -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) + .set("toJSON", &X::to_json) ; v8pp::class_ Y_class(isolate); @@ -165,6 +181,11 @@ void test_class_() check_eq("X::extern_fun(5)", run_script(context, "x = new X(); x.extern_fun(5)"), 6); check_eq("X::extern_fun(6)", run_script(context, "X.extern_fun(6)"), 6); + check_eq("JSON.stringify(X)", + run_script(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(context, "y = new Y(-100); y.konst + y.var"), -1); auto y1 = v8pp::factory::create(isolate, -1);