justjake / quickjs-emscripten

Safely execute untrusted Javascript in your Javascript, and execute synchronous code that uses async functions
https://www.npmjs.com/package/quickjs-emscripten
Other
1.18k stars 94 forks source link

Clarification in newObject method inside context #184

Closed rakeshar3796 closed 1 week ago

rakeshar3796 commented 1 week ago

Hey @justjake, thanks for the wonderful library, I've started exploring the library few weeks now and playing around it.

I've a question related to a scenario, where i've a custom method say getData when called it returns an object. For now it returns an mock object like below,

{
  "name": "User1",
  "age": 21,
  "address": {
    "city": "India"
  }
}

so to return this object what i understood is i need to write code like below

    const getDataHandle = context.newFunction("getData", () => {
      const _object = context.newObject();
      const _nested = context.newObject();
      context.setProp(_nested, "city", context.newString("India"));
      context.setProp(_object, "name", context.newString("User1"));
      context.setProp(_object, "age", context.newNumber(21));
      context.setProp(_object, "address", _nested);
      return _object;
    });

    context.setProp(context.global, "getData", getDataHandle);

like lets say i've a JS Object like

const myObj = {
  "name": "User1",
  "age": 21,
  "address": {
    "city": "India"
  }
}

return context.newObject(myObj); // can this be possible?

instead of iterating the object and setting in context?

Also this helps when i create a function to make external API calls and want to return the result to the host?

rakeshar3796 commented 1 week ago

@justjake any views on this?

justjake commented 1 week ago

Its possible to write such a function yourself using iteration or JSON stringify/parse.

rakeshar3796 commented 1 week ago

Hey @justjake, thanks for the workaround yeah writing own function will help out but for my case JSON stringify/parse won't help.