-
-
Notifications
You must be signed in to change notification settings - Fork 568
/
Copy pathInteropTests.SystemTextJson.cs
104 lines (89 loc) · 3.53 KB
/
InteropTests.SystemTextJson.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System.Reflection;
using System.Text.Json.Nodes;
using Jint.Runtime.Interop;
namespace Jint.Tests.PublicInterface;
public partial class InteropTests
{
[Fact]
public void AccessingJsonNodeShouldWork()
{
const string Json = """
{
"employees": {
"type": "array",
"value": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Jane",
"lastName": "Doe"
}
]
}
}
""";
var variables = JsonNode.Parse(Json);
var engine = new Engine(options =>
{
// make JsonArray behave like JS array
options.Interop.WrapObjectHandler = static (e, target, type) =>
{
var wrapped = new ObjectWrapper(e, target);
if (target is JsonArray)
{
wrapped.Prototype = e.Intrinsics.Array.PrototypeObject;
}
return wrapped;
};
// we cannot access this[string] with anything else than JsonObject, otherwise itw will throw
options.Interop.TypeResolver = new TypeResolver
{
MemberFilter = static info =>
{
if (info.ReflectedType != typeof(JsonObject) && info.Name == "Item" && info is PropertyInfo p)
{
var parameters = p.GetIndexParameters();
return parameters.Length != 1 || parameters[0].ParameterType != typeof(string);
}
return true;
}
};
});
engine
.SetValue("variables", variables)
.Execute("""
function populateFullName() {
return variables['employees'].value.map(item => {
var newItem =
{
"firstName": item.firstName,
"lastName": item.lastName,
"fullName": item.firstName + ' ' + item.lastName
};
return newItem;
});
}
""");
// reading data
var result = engine.Evaluate("populateFullName()").AsArray();
Assert.Equal((uint) 2, result.Length);
Assert.Equal("John Doe", result[0].AsObject()["fullName"]);
Assert.Equal("Jane Doe", result[1].AsObject()["fullName"]);
// mutating data via JS
engine.Evaluate("variables.employees.type = 'array2'");
engine.Evaluate("variables.employees.value[0].firstName = 'Jake'");
Assert.Equal("array2", engine.Evaluate("variables['employees']['type']").ToString());
result = engine.Evaluate("populateFullName()").AsArray();
Assert.Equal((uint) 2, result.Length);
Assert.Equal("Jake Doe", result[0].AsObject()["fullName"]);
// mutating original object that is wrapped inside the engine
variables["employees"]["type"] = "array";
variables["employees"]["value"][0]["firstName"] = "John";
Assert.Equal("array", engine.Evaluate("variables['employees']['type']").ToString());
result = engine.Evaluate("populateFullName()").AsArray();
Assert.Equal((uint) 2, result.Length);
Assert.Equal("John Doe", result[0].AsObject()["fullName"]);
}
}